ASAD PAVEL
← ARCHIVE

Nine Factorio Tools, One Static Site, and One Tiny Worker

How factorio.iampavel.dev turns blueprint strings, circuit logic, quality math, and a 55 MB save file into browser-only tools.

Factorio gives you a circuit network, a blueprint string, and not much else. The game is excellent at making you build the same display panel, the same train stop, or the same mall circuit for the tenth time. I wanted the boring parts to be one paste away.

So I built factorio.iampavel.dev: nine browser-based generators and calculators for Factorio 2.x and Space Age. Pick a tool, configure it, copy a blueprint string, paste it into the game. No account, no install, no upload.

Factorio Blueprint Tools homepage showing nine browser-based generators

A blueprint string is just compressed JSON

Every tool on the site ends in the same place: a Factorio blueprint string. The format is simple enough to implement in an afternoon:

  1. Start with a version byte, usually "0".
  2. Serialize the blueprint object to JSON.
  3. Deflate it with zlib.
  4. Base64-encode the result.

The whole codec is about thirty lines of browser JavaScript:

const deflate = (bytes) =>
	new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"));

export async function encodeBlueprint(obj) {
	const json = JSON.stringify(obj);
	const compressed = await new Response(
		deflate(new TextEncoder().encode(json)),
	).arrayBuffer();
	const bytes = new Uint8Array(compressed);
	let binary = "";
	for (const byte of bytes) binary += String.fromCharCode(byte);
	return "0" + btoa(binary);
}

CompressionStream("deflate") is the browser’s native zlib, which is exactly what Factorio expects. No bundler, no compression library, no Web Worker needed. Decoding is the same pipeline in reverse, with a small concession: if the pasted text starts with {, treat it as decoded JSON instead of a blueprint string.

That decision made every tool easier. The UIs can show the pretty-printed JSON, accept it back, and round-trip through the same code path.

This assumes a browser with CompressionStream (current Chrome, Edge, Firefox, and Safari all have it). The game fixtures are pinned to Factorio 2.1.9, so blueprint keys are versioned with the test fixture rather than assumed to be stable forever.

The Go CLI that taught me the format

Before the browser tools, I wrote factorio-automall, a Go CLI that generates a combinator setup for a roboport network or spaceship hub. It was the project where I learned to stop treating a blueprint as a string and treat it as a typed document.

The CLI reads a JSON dump of Factorio’s item and recipe prototypes, walks every recipe including its ingredients, and emits blueprint JSON. The Go types are the schema. This is the whole top-level blueprint:

type Factorio struct {
	Blueprint *Blueprint `json:"blueprint"`
}

type Blueprint struct {
	Description string    `json:"description"`
	Icons       []*Icon   `json:"icons"`
	Entities    []*Entity `json:"entities"`
	Wires       [][]int   `json:"wires,omitempty"`
	Item        string    `json:"item"`
	Version     string    `json:"version"`
}

The recipe side is just as plain. The extracted game data in the repo (recipe/vanilla-2.0.10.json and recipe/space-age-2.0.11.json) contains items, recipes, ingredients, results, categories, and stack sizes:

data, err := recipe.ReadFile(filename)
if err != nil {
	log.Fatalf("Error reading file: %v", err)
}

for _, rec := range data.Recipes {
	if shouldIgnore(rec) {
		continue
	}
	for _, quality := range qualities {
		for _, ingredient := range rec.Ingredients {
			addCondition(ingredient.Name, int(ingredient.Amount), quality)
		}
	}
}

That project taught me the parts that matter later:

  • Items, fluids, and virtual signals are different signal types, not just strings.
  • Recipe ingredients are the input to circuit conditions; results are not.
  • Quality is part of a signal identity, not a cosmetic label.
  • A blueprint version is a number that the game checks.
  • Constant combinators use negative values when the same signal is also used as a key.

The browser tools reuse the same mental model. They differ in where the data comes from and how the output is produced: factorio-automall walks recipes and writes typed Go structs, while the site ships pre-extracted game data and builds the same JSON in the browser.

The live Auto Mall Generator is the productized version of that CLI. It keeps the recipe-data → blueprint-JSON path, then adds multi-item goals, quality tiers, stock bands, and a latched set-recipe circuit.

What is on the site

The tools split into three groups.

Generators produce a blueprint directly:

  • Display Gauge Generator: a circuit-driven progress bar with a color gradient, threshold icons, and a percentage label for any signal.
  • Auto Research Circuit: queues technologies when science-pack stock passes a threshold, with an editable priority list and status panels.
  • Auto Mall Generator: one assembler crafts a whole mall, using a latched set-recipe circuit that ignores ingredient dips.
  • Train Stop Generator: named, colored stops from a format template, with cargo icons, train limits, and priority.
  • Circuit Builder: compiles a text circuit language into one wired blueprint.

Calculators answer a question before you build:

Inspectors work on things you already have:

  • Blueprint Diff: compares two blueprint strings and shows entities added, removed, or reconfigured, plus wires connected or cut.
  • Blueprint Library Browser: opens blueprint-storage-2.dat locally and searches every blueprint label.

Nine tools, one static site, no user data leaving the browser. In the 30 days before 2 December 2026, the site had about 16,000 unique visitors.

Designing the pages

I designed the tool pages to match Factorio’s in-game GUI: compact controls, beveled panels, warm dark surfaces, and orange accents. The background is from the official Factorio website.

The gauge has a hard limit of 100 messages

The display gauge is the tool I use most, and it is the one with the strangest constraint. A Factorio display panel accepts at most 100 messages. A gauge that wants one message per value is out of luck past 100.

Instead, the generator spreads up to 100 threshold steps across the whole [min, max] range. Each step is gated by input ≤ threshold, and the top step flips to input ≥ threshold so overflow reads as full. The panel shows the first matching step, so the live signal value becomes a position on the bar.

The comparators also have to be gap-free for integer signals. That is the kind of detail that is easy to get wrong once and then impossible to notice until a value lands exactly on a threshold in-game. The generated panel handles it at the edges, not just in the pretty preview.

The core of the step builder is small enough to read:

const STEP_LIMIT = 100;
const LESS_EQUAL = "≤";
const GREATER_EQUAL = "≥";

const count = Math.min(STEP_LIMIT, span + 1);
const raw = Array.from({ length: count }, (_, i) => {
	const frac = count === 1 ? 1 : i / (count - 1);
	return { value: Math.round(min + frac * span), isTop: i === count - 1 };
});

return raw.map((step) => ({
	value: step.value,
	comparator: step.isTop ? GREATER_EQUAL : LESS_EQUAL,
	constant: step.isTop ? raw[count - 2].value + 1 : step.value,
}));

The top step uses ≥ previousValue + 1, not ≥ value. If the top threshold were the same as the second-highest threshold, both conditions could match at the boundary. The extra integer makes the ranges disjoint for every possible signal value.

The 100-step limit also forces a value to be dropped on a 0–100 gauge. Naive rounding drops 50, which is the number everyone looks at. The builder detects that case and shifts the step below the gap so 49 is the dropped value instead:

const mid = min + span / 2;
if (Number.isInteger(mid)) {
	const values = raw.map((s) => s.value);
	const below = values.indexOf(mid - 1);

	if (below !== -1 && !values.includes(mid) && values.includes(mid + 1)) {
		raw[below].value = mid;
	}
}

Display Gauge Generator showing a water-level gauge with a live preview and blueprint string

The tests pin the exact property that matters: every value maps to exactly one step, and the fill never goes backwards.

test("uses ≤ for all steps except the top (≥), with gap-free constants", () => {
	const params = paramsOf({ min: 0, max: 5000 });
	params.forEach((p, i) => {
		assert.equal(p.condition.comparator, i === params.length - 1 ? "≥" : "≤");
	});
	const top = params.at(-1).condition.constant;
	const prev = params.at(-2).condition.constant;
	assert.equal(top, prev + 1);
});

A circuit builder that treats text as the source of truth

Point-and-click combinator editors are fine until a circuit grows past a screen. I wanted something closer to code: describe the combinators and wires as text, then compile the whole thing into a blueprint.

DECIDER low_iron
  WHEN iron-plate < 100
  OUT signal-check = 1

ARITH double
  signal-check * 2 -> signal-A

WIRE red: low_iron.out -> double.in
WIRE green: double.out -> low_iron.in

Circuit Builder showing a program, syntax-highlighted editor, and generated blueprint

The parser turns that into a semantic model instead of a syntax tree. It runs in five stages: lower macros like REPEAT and MATH, scan blocks line by line, parse each block kind, resolve wires and asserts after all blocks are read, then emit nodes and wires. Every generated line keeps its original source line number, so an error still points at the line the user typed instead of at the expansion.

The most involved lowering is the LUT builtin. It is a small language of its own: range tables, criteria tables, hysteresis latches, upcycling tables, and an optional LOCK priority mode. A latch lowers to one constant combinator and one decider with a green feedback wire; the table values are negative identities walking toward zero, and the held row reads exactly one above its own identity through the feedback.

LOCK makes the table an exclusive priority decoder. Each row gets a spare virtual signal as a cipher. Later rows are gated on earlier rows’ ciphers being zero, so at most one row can be active. The cipher allocator avoids every signal already used in the program:

const LOCK_CIPHER_POOL = [
	"signal-lock",
	"signal-unlock",
	"signal-check",
	"signal-deny",
	"signal-no-entry",
	"signal-alarm",
	// ...letters and digits as fallbacks
];

function lockCiphers(rows, used, taken) {
	const ciphers = [];
	const avoid = new Set(used);
	for (const row of rows) avoid.add(baseSignal(row.out));

	rows.forEach((row, idx) => {
		for (const name of LOCK_CIPHER_POOL) {
			if (avoid.has(name)) continue;
			avoid.add(name);

			let value = -(idx + 1);
			while (taken.has(value)) value -= 1000;
			taken.add(value);

			ciphers.push({ name, value, srcLine: row.srcLine });
			break;
		}
	});
	return ciphers;
}

Negative values are deliberate. Label-mode rows emit 1, so a cipher can never collide with a normal output. Every generated line still carries srcLine, including the rows produced by the LUT expander.

One example of a smaller lowering is the one-way wire operator. Factorio wires are physically undirected, so => cannot be a wire. The compiler lowers it to an arithmetic combinator that copies signal-each with + 0, which creates a one-way hop with a one-tick delay:

WIRE green: a -> b => c

# lowers to:
ARITH diode-1
  signal-each + 0 -> signal-each
WIRE green: a -> b -> diode-1.in
WIRE green: diode-1.out -> c

The parser and builder share the same model, but the simulator gets its own graph. Wire networks are computed with union-find: every wire merges its two endpoints, and radars join or leave networks by channel.

export function buildNetworks(model) {
	const uf = makeUnionFind();
	for (const wire of model.wires) {
		uf.union(
			endpointKey(wire.a.name, wire.a.port, wire.color),
			endpointKey(wire.b.name, wire.b.port, wire.color),
		);
	}
	// Radars on the same UNIVERSE channel share a network.
	for (const radar of model.nodes.filter((n) => n.kind === "radar")) {
		// ...
	}
	return uf;
}

Signal counts wrap exactly like the game; arithmetic goes through BigInt.asIntN(32, ...) rather than floating-point JavaScript. But the interesting part is not the evaluator. It is the layout.

A circuit blueprint has fixed coordinates. Put combinators in declaration order and long wires silently exceed the game’s reach limit. The layout pass treats node order as an optimization problem: minimize dropped wires first, then total wire length.

The score is evaluated against a serpentine grid. Greedy seating gets a starting order, then deterministic simulated annealing swaps slots:

function annealOrder(model, order) {
	const n = order.length;
	if (n < 3) return order;

	const rand = xorshift(0x9e3779b9 ^ n); // deterministic, not Math.random
	const iterations = Math.min(6000, 30 * n * n);
	let current = order.slice();
	let currentScore = scalarScore(wireScore(model, current));
	let best = current.slice();
	let bestScore = currentScore;
	const t0 = Math.max(1, currentScore * 0.05);

	for (let i = 0; i < iterations; i++) {
		const temp = t0 * (1 - i / iterations) + 1e-6;
		const a = Math.floor(rand() * n);
		let b = Math.floor(rand() * n);
		if (a === b) b = (b + 1) % n;

		[current[a], current[b]] = [current[b], current[a]];
		const score = scalarScore(wireScore(model, current));
		const delta = score - currentScore;
		if (delta <= 0 || rand() < Math.exp(-delta / temp)) {
			currentScore = score;
			if (score < bestScore) {
				bestScore = score;
				best = current.slice();
			}
		} else {
			[current[a], current[b]] = [current[b], current[a]];
		}
	}
	return best;
}

wireScore builds the minimum spanning tree for each wire component, sums the distances, and counts edges that exceed their endpoints’ reach. Dropped wires dominate the score:

const scalarScore = (s) => s.drops * 1e4 + s.length;

function wireScore(model, order) {
	const pos = rowPositions(model, orderToColumns(order));
	let drops = 0;
	let length = 0;

	for (const component of components) {
		for (const edge of spanningEdges(component)) {
			length += edge.dist;
			if (edge.dist > edge.limit) drops++;
		}
	}
	return { drops, length };
}

The PRNG is seeded from the node count, the iteration budget is deterministic, and positions are quantized to the grid. Same program in, same bytes out. The scheduler is allowed to be clever because the output is not allowed to be random.

The model feeds three things:

  • A blueprint builder that lays out columns depth-first, adds relay poles for long wire spans, and serializes the result. The same program always produces the same bytes.
  • A tick simulator with union-find wire networks, 1-tick combinator delay, and signed 32-bit integer math. It can run until a breakpoint, show live condition verdicts, scrub back through 120 ticks, and fake reader inputs.
  • An SVG wiring diagram with entity sprites and port-aware routing.

That simulator is not a full game clone, and it does not pretend to be. It exists to catch the class of bug where a latch never releases or a signal arrives one tick late, before the blueprint reaches a real save.

Quality math is a Markov chain, not a spreadsheet

The quality upcycling calculator looks like a table of percentages. Underneath, it is an absorbing Markov chain over the quality tiers. Each craft can stay at its current tier, upgrade, or produce scrap. The recycler feeds materials back into the loop, and the whole thing converges on expected output per tier.

The calculator factors in machine quality, module quality and tier, productivity, recycler modules, and which tiers you keep. It also plots the productivity-versus-quality tradeoff, because “more quality modules” is not always the answer when you also need throughput.

A single craft has a cascading quality distribution, not a flat 10% chance. The first roll can upgrade one tier, but a second roll can upgrade again. The distribution is geometric until it hits the cap:

export function qualityDist(q, fromIdx, maxIdx) {
	const dist = new Array(5).fill(0);
	const cap = Math.min(maxIdx, 4);
	if (fromIdx >= cap || q <= 0) {
		dist[Math.min(fromIdx, cap)] = 1;
		return dist;
	}

	dist[fromIdx] = 1 - q;
	let remaining = q;
	for (let k = 1; fromIdx + k <= cap; k++) {
		const target = fromIdx + k;
		if (target === cap) {
			dist[target] += remaining;
			break;
		}
		const p = q * (1 - CASCADE) * Math.pow(CASCADE, k - 1);
		dist[target] += p;
		remaining -= p;
	}
	return dist;
}

The full loop is an absorbing Markov chain. M is the transition matrix for recycled items, G is the reward matrix for kept items, and f is the input feed. The solver computes expected yields by solving x(I - M) = f instead of iterating until the numbers stop moving:

function solveLinear(M, f) {
	const n = f.length;
	const A = Array.from({ length: n }, (_, i) => {
		const row = [];
		for (let j = 0; j < n; j++) row.push((i === j ? 1 : 0) - M[j][i]);
		row.push(f[i]);
		return row;
	});

	for (let col = 0; col < n; col++) {
		let pivot = col;
		for (let r = col + 1; r < n; r++) {
			if (Math.abs(A[r][col]) > Math.abs(A[pivot][col])) pivot = r;
		}
		[A[col], A[pivot]] = [A[pivot], A[col]];

		const d = A[col][col];
		if (Math.abs(d) < 1e-15) continue;
		for (let j = col; j <= n; j++) A[col][j] /= d;

		for (let r = 0; r < n; r++) {
			if (r === col) continue;
			const factor = A[r][col];
			for (let j = col; j <= n; j++) A[r][j] -= factor * A[col][j];
		}
	}
	return A.map((row) => row[n]);
}

keepMask changes the matrix construction, not the solver. Keeping a tier moves that output into G; everything else goes into toRecycle and then through the recycler’s own quality distribution. The productivity-versus-quality sweep calls the same solver for every module split, so there is no second formula to drift.

The labs calculator is the same idea with less state: research speed, research productivity, module effects, beacons with square-root diminishing returns, and biolab speed. The output is the exact lab count, the rounded count, and science-pack consumption per minute.

Both calculators use constants extracted from the game data rather than numbers I guessed.

Reading a 55 MB binary file in the browser

The Blueprint Library Browser is the tool I expected to be impossible without a backend. Factorio stores your blueprint library in blueprint-storage-2.dat, a binary file that can be tens of megabytes.

The file is not documented, but it is structured. The global header starts with four little-endian version fields, a boolean, a migration count, and length-prefixed migration pairs. Every record re-embeds that same header, which means the file’s own first bytes work as a scan signature. Each blueprint label sits length-prefixed immediately before its record.

So the browser does a structural scan: find the header signature, walk record starts, read the label window before each one, and list the results. No upload, no server, no full entity decode.

The signature is the first migration pair, 04 "base". Finding it at the start of the file gives a byte sequence to search for:

const probe = [0x04, 0x62, 0x61, 0x73, 0x65]; // 04 "base"

function buildSignature(bytes) {
	for (let i = 8; i < Math.min(bytes.length - probe.length, 64); i++) {
		if (probe.every((b, j) => bytes[i + j] === b)) {
			return bytes.slice(0, i + probe.length);
		}
	}
	return null;
}

Each record is preceded by <u8 length><label bytes> 00 00 ff <u32 size>. The scanner walks backward from a record start inside a bounded window, validates the label as printable UTF-8, and keeps the offset. It never decodes entity payloads.

The label finder is deliberately conservative. It checks the fixed 00 00 ff suffix, the u32 size, the length prefix, and that every label byte is printable:

function labelBefore(bytes, recordAt) {
	if (recordAt < 7 || bytes[recordAt - 5] !== 0xff) return null;

	const size =
		bytes[recordAt - 4] |
		(bytes[recordAt - 3] << 8) |
		(bytes[recordAt - 2] << 16) |
		((bytes[recordAt - 1] << 24) >>> 0);

	if (bytes[recordAt - 6] !== 0 || bytes[recordAt - 7] !== 0) {
		return { label: null, size };
	}

	const windowEnd = recordAt - 7;
	const windowStart = Math.max(0, windowEnd - 300);

	for (let i = windowEnd - 1; i >= windowStart; i--) {
		const len = bytes[i];
		if (len === 0 || i + 1 + len !== windowEnd) continue;

		let ok = true;
		for (let j = i + 1; j < windowEnd; j++) {
			if (!printable(bytes[j]) && bytes[j] < 0x80) {
				ok = false;
				break;
			}
		}
		if (!ok) continue;

		return {
			label: new TextDecoder().decode(bytes.slice(i + 1, windowEnd)),
			size,
		};
	}
	return { label: null, size };
}

That is enough to build a searchable label index without shipping a 55 MB save file anywhere. It is also why the browser only promises labels, not full blueprint extraction: entity payloads are version-coupled in ways a label scanner never has to care about.

On a real 55 MB file, a proof of concept recovered 3,425 of 3,480 labels. That is enough for a searchable library. Full entity decoding is a different problem and version-coupled, so the browser deliberately stops at labels rather than pretending it can export every blueprint safely.

Testing against the game, not just against myself

The most useful decision was to test the output against Factorio itself.

The test suite uses Node’s built-in test runner. There are parser tests for exact models and error messages, builder tests for positions and wire connections, encode/decode round trips, and a sweep that parses and builds every shipped template. A browser end-to-end test skips itself when Chromium is not available.

Then there is the part that matters: a fixture from headless Factorio 2.1.9. I imported a generated blueprint into the real game and pinned the resulting keys. If the builder and the game disagree about an entity key, the test fails. That is a much better signal than a snapshot I wrote myself.

The round-trip test takes the game’s own re-export, parses it back to the DSL, rebuilds it, and checks the keys the game normalized:

test("the game's own re-export of our kitchen-sink blueprint imports clean", async () => {
	const decoded = JSON.parse(
		await readFile(new URL("./fixtures/game-roundtrip.json", import.meta.url), "utf8"),
	);

	const { text, warnings } = circuitTextFromBlueprint(decoded);
	assert.deepEqual(warnings, []);

	const { model, errors } = parseCircuitText(text, catalog);
	assert.deepEqual(errors.filter((e) => e.severity === "error"), []);

	const { blueprint } = buildCircuitBlueprint(model);
	const speaker = blueprint.entities.find((e) => e.name === "programmable-speaker");
	assert.equal(speaker.parameters.playback_mode, "global");
});

The gauge tests are similarly specific about invariants instead of pixels:

test("never exceeds 100 steps no matter how large the range", () => {
	assert.equal(paramsOf({ min: 0, max: 100000 }).length, 100);
	assert.equal(paramsOf({ min: 0, max: 5000 }).length, 100);
});

test("displayedStep maps every value to a step, monotonic in fill", () => {
	const steps = buildSteps({ min: 0, max: 100000 });
	let prevPct = -1;
	for (let value = 0; value <= 100000; value += 911) {
		const step = displayedStep(steps, value);
		assert.ok(step.pct >= prevPct);
		prevPct = step.pct;
	}
});

The second rule is deterministic output. The same program must produce a byte-identical blueprint. That makes diffs meaningful, tests stable, and share links trustworthy.

Static by default, with one small escape hatch

The site is a set of static HTML pages deployed as a Cloudflare Workers Static Assets project. There is no application server, no database, and no account system.

Share links encode the tool state as base64url JSON. Configs are diffed against defaults first, so a link carries only the fields that changed:

export function encodeState(obj) {
	const bytes = new TextEncoder().encode(JSON.stringify(obj));
	let bin = "";
	for (const b of bytes) bin += String.fromCharCode(b);
	return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

export function diffFrom(defaults, obj) {
	const out = {};
	for (const [key, value] of Object.entries(obj)) {
		if (JSON.stringify(value) !== JSON.stringify(defaults[key])) {
			out[key] = value;
		}
	}
	return out;
}

For links that get too long, a small Worker stores the state in KV behind a short code and serves a bootstrap page that hands the state to the tool. It has a per-IP rate limit, validates the target, and rejects cross-origin posts. If the endpoint is unavailable, the client falls back to the long URL. That is the one piece of server-side code, and it exists to make a URL shorter or survive a chat client, not to run the tools.

The tools have no runtime backend. The only server-side code is that URL shortener.

One credit note: the virtual signal sprites are extracted from a local Factorio install, item sprites come from the FactorioLab dataset, and Factorio is a trademark of Wube Software. This site is not affiliated with Wube.

What I would do differently

I would start with the game fixture earlier. A lot of time went into getting blueprint keys and circuit semantics right by reading exports and guessing at behavior. One import into headless Factorio would have settled several arguments in minutes.

I would also keep the “semantic model” boundary from day one. The Circuit Builder became much easier to extend once parsing, simulation, layout, and serialization stopped sharing the same data structure. The model is the contract; everything else is a consumer.

And I would resist adding a tenth tool until the ninth has tests. The site is already a toolbox. The value is not more surface area. It is that each tool produces something you can paste into the game and trust.

If you play Factorio 2.x, start with the Display Gauge Generator or the Circuit Builder. If something breaks, the source is on GitHub.

COMMENTS

GitHub sign-in required. Keep it useful.