# Windows Build Guide — PayBench / SimulatorPOS

> 📘 **Schema v2 disponible desde 2026-05-20**: hosts y pinpads ahora se configuran por separado y se combinan via `app.active_host` + `app.active_pinpad`. Cross-cutting `auth_providers`/`tls_options`/`header_sets` referenciables por host. Autodetect PINPAD via `config/known-pinpads.json` (13 modelos editables por QA). Ver [CONFIGURATION-GUIDE.md §2](CONFIGURATION-GUIDE.md) para el shape completo y [QA-DESKTOP-WRAPPERS.md](QA-DESKTOP-WRAPPERS.md) para el plan de pruebas. El schema v1 legacy descrito acá sigue funcionando.


> **Audience**: a Windows developer who needs to produce every distributable
> from a fresh Windows machine — five standalone EXEs (PKG, NCC, SEA, Bun,
> Deno), the Electron installer/portable, and the Tauri sidecar app.
>
> **Last verified**: 2026-05-13 from macOS arm64 (cross-build) and against
> the Windows CI matrix in `.github/workflows/build.yml`.

There is a separate cross-build path for macOS/Linux developers documented
at the end of this file.

---

## 1. Prerequisites

Install the following — in this order — before cloning the repo. All
versions are pinned in CI; older versions break the native module ABI.

| Tool | Version | Install |
|---|---|---|
| **Node.js** | 24.13.0 LTS | https://nodejs.org/en/download — pick the Windows x64 MSI. Pin via `nvm-windows`. |
| **Bun** | ≥ 1.3.0 | `powershell -c "irm bun.sh/install.ps1 \| iex"` |
| **Deno** | ≥ 2.7.0 | `powershell -c "irm https://deno.land/install.ps1 \| iex"` |
| **Git** | latest | https://git-scm.com/download/win (Git Bash is needed for any `compile:*:current` script that uses `$(...)` substitution) |
| **Python** | 3.10–3.12 | https://www.python.org/downloads — required by `node-gyp` for any native-module rebuild. |
| **Visual Studio Build Tools 2022** | latest | https://visualstudio.microsoft.com/visual-cpp-build-tools/ — select the **"Desktop development with C++"** workload (provides MSVC v143, Windows 10/11 SDK, and MSBuild). |
| **Rust toolchain** | 1.78+ | `winget install Rustlang.Rustup` then `rustup default stable` — **only needed for Tauri**. |
| **WiX Toolset v3.14** | 3.14 | `winget install --id WiXToolset.WiXToolset --version 3.14.0` — only if you want Tauri to produce an MSI installer; the `.exe` works without it. |

Optional but recommended:

- **GitHub CLI** (`gh`) for pulling PRs and uploading artifacts.
- **PowerShell 7+** for nicer scripting; 5.1 (built-in) works too.

> **Heads up on PATH**: every install above needs to land in `PATH`. If `node`,
> `bun`, `deno`, `cargo`, or `cl.exe` are not found in a fresh `cmd.exe`, restart
> the shell and re-check.

---

## 2. First-time clone

```cmd
git clone https://github.com/eldo-loguzzo/POS-Simulator.git
cd POS-Simulator
npm install
```

`npm install` will:

1. Pull all dependencies (~1000 packages, ~1.5 GB).
2. Download the **Windows x64 prebuild** of `sqlite3` and `better-sqlite3` via
   `node-pre-gyp` / `prebuild-install`. After the install you should see
   `node_modules\sqlite3\build\Release\node_sqlite3.node` reporting as
   `PE32+ executable (DLL) (GUI) x86-64` (use `dumpbin /headers` from a VS
   Developer prompt to confirm if curious).
3. Compile any package that does NOT publish a prebuild — that's why the
   Visual Studio Build Tools + Python are mandatory.

If `npm install` ever produces a Mach-O or ELF binary for sqlite3 (because
you copy/pasted a `node_modules` folder from another machine), delete
`node_modules` and re-install.

---

## 3. Build every standalone EXE — happy path

Every script below assumes a clean `npm install` already ran on this Windows
machine. Run from the project root in **Git Bash** (the `compile:*:current`
scripts use `$(node scripts/platform-suffix.mjs)` which only works in bash).

```bash
# Compile a TypeScript build (required by every method)
npm run build

# 1. PKG bundle (largest, ~470 MB)
npm run compile:pkg:current
# → bin/SimulatorPOS-pkg-win-x64.exe

# 2. NCC bundle + PKG (~95 MB)
npm run compile:ncc:current
# → bin/SimulatorPOS-ncc-win-x64.exe

# 3. SEA — Node.js Single Executable Application (~120 MB)
npm run compile:sea:current
# → bin/SimulatorPOS-sea-win-x64.exe
# NOTE: SEA needs Node.js 24 LTS from nodejs.org, NOT from Chocolatey.
# Chocolatey's Node sometimes ships a build without the postject binding.

# 4. Bun standalone (~120 MB)
npm run compile:bun:current
# → bin/SimulatorPOS-bun-win-x64.exe
# Bun marks sqlite3 as --external, so the .exe expects
# build\Release\node_sqlite3.node next to it at runtime. The portable
# distribution folder produced by `npm run dist:qa:win` ships this file
# alongside the exe; see Section 5.

# 5. Deno standalone (~100 MB)
npm run compile:deno:current
# → bin/SimulatorPOS-deno-win-x64.exe
# Deno embeds node_sqlite3.node via --include, so the .exe is self-contained.

# All five at once
npm run compile:all:current
```

If you instead want **all 5 variants for win-x64 in one go** (handy if
your current machine happens to be ARM64 but you want x64 artifacts):

```bash
npm run compile:pkg:win-x64
npm run compile:ncc:win-x64
npm run compile:bun:win-x64
npm run compile:deno:win-x64
# SEA is host-only: you have to be on a win-x64 machine.
```

---

## 4. Electron desktop wrapper (the Friday-demo deliverable)

Electron is what we ship to a Windows 10 box that only has Internet
Explorer — it bundles its own Chromium so the UI looks identical to the
QA-validated browser deployment, and it gives the PINPAD/USB path a real
runtime.

```bash
# One-time: install Electron + electron-builder (~200 MB)
npm run electron:install

# Build the installer + portable + unpacked folder
npm run electron:dist:win
```

Outputs in `bin/electron/`:

- `PayBench Setup 0.6.0.exe` — NSIS installer (x64 + arm64 fat installer)
- `PayBench 0.6.0.exe` — portable single-file (x64 + arm64)
- `win-unpacked/` — the unpacked Windows x64 directory (ZIP this for a
  "no-install" deployment)
- `win-arm64-unpacked/` — unpacked Windows ARM64 directory

The `electron-app/package.json` sets `"npmRebuild": false`, so the native
modules currently in `node_modules` are shipped as-is. On a Windows box
that means the Windows prebuilds you got from `npm install`. On macOS you
need the cross-build path (Section 7).

To smoke-test the portable .exe without installing:

```cmd
"bin\electron\PayBench 0.6.0.exe"
```

It should open a Chromium window, the backend (Node.js) should boot on
port 9095, and the QA web UI should render. Close the window → the
backend posts `/api/shutdown` and the child process exits.

---

## 5. Portable QA bundle (single ZIP for testers)

For internal QA you usually want a self-contained folder, not an installer.
`scripts/build-qa-portable.mjs` produces exactly that — copies dist, NCC
bundle, prebuilds, config, public, templates into a versioned folder ready
to ZIP and drop on any Windows machine.

```bash
npm run dist:qa:win
```

Produces `dist-qa/SimulatorPOS-qa-win-x64-<date>/` with:

- `SimulatorPOS-ncc.exe` (smaller, faster to copy than PKG)
- `build/Release/node_sqlite3.node` and `better_sqlite3.node` (PE32+ x86-64)
- `serialport prebuilds/win32-x64/@serialport+bindings-cpp.node`
- `config/`, `public/`, `templates/`, `data/`, `logs/`

This bundle is what the QA team drops on the demo Windows 10 box.

---

## 6. Tauri desktop wrapper

Tauri ships a much smaller binary (~15 MB) by using the host OS WebView —
on Windows that's WebView2 (preinstalled on Win10 ≥ 1809 and Win11). Note:
**Tauri will NOT help on a fresh Win10 box that only has IE** because IE
is not WebView2. For that scenario use Electron (Section 4).

### 6.a — Building Tauri on Windows itself

For systems that DO have WebView2:

```bash
# 1. Verify Rust is installed
cargo --version    # expect 1.78+
rustc --version

# 2. Tauri CLI is already in the project's devDependencies
npm run build       # backend dist/ must exist first

# 3. Build the NCC sidecar (the Node backend that Tauri spawns)
npm run compile:ncc:current
# Tauri's sidecar binary path is configured in tauri-app/src-tauri/tauri.conf.json

# 4. Build the Tauri app
cd tauri-app
cargo tauri build
# → bin/tauri/PayBench_0.6.0_x64-setup.exe   (NSIS installer)
# → bin/tauri/PayBench_0.6.0_x64_en-US.msi   (only if WiX is installed)
# → src-tauri/target/release/PayBench.exe    (the unsigned portable .exe)
```

For dev iteration (auto-reload):

```bash
cd tauri-app
cargo tauri dev --no-watch
```

### 6.b — Building Tauri for Windows from macOS / Linux (Docker)

Tauri's cross-compile toolchain is fragile when set up by hand (mixes
mingw or xwin, rust-lld, MSVC headers, NSIS). We package the whole stack
inside a Docker image — `paybench/tauri-windows-builder` — so any host
that has Docker can produce the same Windows binary.

```bash
# 1. Build the image once (~15-25 min, ~5 GB)
npm run tauri:builder:image

# 2. Build the Tauri Windows .exe inside the container
npm run tauri:build:win:docker
# → bin/tauri/PayBench-tauri-win-x64.exe
```

The wrapper script (`scripts/build-tauri-windows.sh`) also:
- Builds the NCC sidecar with the Windows native-module swap (Section 7),
  so the Node backend embedded in Tauri's sidecar is the Windows x64
  variant.
- Mounts the repo at `/workspace` so the build output ends up in
  `tauri-app/src-tauri/target/x86_64-pc-windows-msvc/release/PayBench.exe`,
  then copies it to `bin/tauri/PayBench-tauri-win-x64.exe`.

To share the image with another machine (skipping the long first build):

```bash
docker save paybench/tauri-windows-builder:latest | gzip > tauri-builder.tar.gz
# → tauri-builder.tar.gz (~5 GB compressed)

# On the other host:
docker load < tauri-builder.tar.gz
```

Why Docker and not a native cross-compile? On macOS arm64 you'd still
need: Rust + the `x86_64-pc-windows-msvc` target, `xwin` to splat the
MSVC SDK locally (~4 GB), `lld` as the linker, NSIS for the installer,
and the Node toolchain to build the sidecar. Wrapping all of that in
the Dockerfile keeps the host clean and gives a byte-reproducible build
environment.

What we did NOT package inside Docker: Wine. xwin gives `rust-lld` the
MSVC headers and libraries it needs at link time, so the build itself
never invokes a Windows .exe. If you ever need to run NSIS/signtool from
inside the container you can add Wine64 to the Dockerfile, but the
default image stays slim by avoiding it.

---

## 7. Cross-building Windows artifacts from macOS / Linux

If your dev machine is macOS or Linux you can produce every Windows
artifact — including Tauri — without ever touching a Windows machine.
The standalone EXEs + Electron use a native-module swap; Tauri runs in
a Docker container that has Rust + xwin (Microsoft SDK) + lld.

The trick is that the .node native modules currently in `node_modules`
are for the host's OS/arch. Before packaging we swap them out with the
Windows prebuilds shipped in `prebuilds-cache/win32-x64/`, then restore
afterwards.

```bash
# Cross-build all 4 standalone EXEs + Electron
npm run compile:pkg:win-x64:cross
npm run compile:ncc:win-x64:cross
npm run compile:bun:win-x64:cross
npm run compile:deno:win-x64:cross
npm run electron:dist:win:cross
```

Each `:cross` script does:

1. `node scripts/swap-native-modules.mjs win32-x64` — copies
   `prebuilds-cache/win32-x64/{node_sqlite3,better_sqlite3}.node` over
   `node_modules/{sqlite3,better-sqlite3}/build/Release/*.node`, with the
   host binaries backed up to `.swap-backup/`.
2. The normal compile/package step (PKG, Bun, Deno, NCC, electron-builder).
3. `node scripts/swap-native-modules.mjs restore` — puts the host binaries
   back so `npm test`, `npm start`, etc. work for the dev afterwards.
   This runs even if the build step fails (`;` separator, not `&&`).

If you ever need to refresh the win32-x64 prebuilds in
`prebuilds-cache/`, the canonical sources are:

- `sqlite3`: https://github.com/TryGhost/node-sqlite3/releases (download
  `node-v131-win32-x64.tar.gz` for Node 24 ABI, extract `node_sqlite3.node`).
- `better-sqlite3`: https://github.com/WiseLibs/better-sqlite3/releases
  (download the matching `better-sqlite3-vX.X.X-node-vXXX-win32-x64.tar.gz`,
  extract `build/Release/better_sqlite3.node`).

---

## 8. Build / test remote on a Windows machine via SSH (recommended for QA validation)

A third workflow added 2026-05-15 for **pre-delivery validation**: instead
of cross-building (§7) and trusting Wine smoke, you keep a real Windows
machine (typically a UTM VM on macOS arm64) reachable via SSH from your
dev box, then:

- **Test** the cross-built ZIP against the real Windows runtime in ~3 min
  via `smoke-windows-vm.bat` (lo más usado — ver
  [QA-SMOKE-TEST.md §4.5](QA-SMOKE-TEST.md)).
- **Build** the artifacts natively on Windows when you need to test
  PINPAD USB or WebView2 paths that Docker/Wine can't reproduce.

### 8.1 When to choose this path

| Necesidad | Cross-build (§7) | SSH a Windows (this section) |
|---|---|---|
| Generar binarios para QA | ✅ Más rápido | ✅ (~25 min) |
| Validar PE32+ no corrupto | ✅ Wine smoke | ✅ Smoke real |
| Validar WebView2 + Tauri ventana | ❌ Wine no implementa WebView2 | ✅ |
| Validar Knex SQLite3 (`Client_SQLite3.initializeDriver`) | ⚠️ Wine 9 falla antes (BCryptGenRandom) — **oculta el bug real** | ✅ |
| Validar PINPAD USB serial real | ❌ No hay puerto | ✅ (con USB passthrough de UTM) |
| Reproducir crash `paybench-startup.log` | ⚠️ Parcial | ✅ |

> **Hallazgo 2026-05-15**: el ZIP del 2026-05-14 pasaba Wine smoke (PASS
> partial), pero al ejecutarlo en Win11 real fallaban 3 bugs (NCC sidecar
> + Bun + Deno) que Wine ocultaba. Ver
> [CHANGELOG §"Validación en Windows 11 real ARM64"](../CHANGELOG.md).

### 8.2 Setup flota Windows + SSH (one-time)

Detallado en QA-SMOKE-TEST.md §4.5.1-§4.5.3. **Desde 2026-05-16 hay 3
nodos Windows en paridad** (cualquiera sirve, se usan también como
backup mutuo):

| Host SSH | Tipo | User Windows | Cuándo usar |
|---|---|---|---|
| `vm-windows-utm-air-m5` | VM UTM en MacBook Air M5 | `eldo.loguzzo` | Default — el más cercano si trabajás en el Air |
| `vm-windows-utm-mini-m2` | VM UTM en Mac Mini M2 | `eldo.loguzzo` | Backup si air-m5 está apagada / Mini M2 si Air no está disponible |
| `surface-pro-x` | Hardware real (Surface Pro X) | `eldol` (cuenta `eldo.loguzzo@outlook.com`) | Hardware ARM64 real — útil para validar issues que solo aparecen en máquinas físicas. **Caveat**: el bat usa `/ru eldo.loguzzo` hardcodeado, patchear a `/ru eldol` antes de correr |

**Setup común en cada nodo Windows**:

| Componente | Cómo |
|---|---|
| **UTM 4.7+** (macOS host, solo para las VMs) | `brew install --cask utm` |
| **CrystalFetch** (macOS host, solo para las VMs) | `brew install --cask crystalfetch` (download Win11 ARM64 ISO) |
| **Windows 11 ARM64 24H2** | x64 emulation built-in → corre todos los `*-win-x64.exe` |
| **OpenSSH Server** | PowerShell elevado: `Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 ; Start-Service sshd ; Set-Service -Name sshd -StartupType Automatic` |
| **Tailscale** | `tailscale.com/download` — recomendado, da IP estable `100.x.x.x` |
| **SSH key auth** | macOS → cada nodo: `ssh-keygen -t ed25519 ; ssh-copy-id <user>@<host>` |
| **Firewall Node.js pre-aprobado** | `New-NetFirewallRule` — evita los modales "Seguridad de Windows" durante el smoke |
| **Node.js + toolchain** (opcional, solo para BUILD remoto) | Pre-requisitos §1 de este doc, instalados nativamente |
| **Claude Code CLI** (opcional, para orquestación LLM) | `winget install OpenJS.NodeJS ; npm install -g @anthropic-ai/claude-code ; claude` (primer login OAuth) |

Verificación:
```bash
ssh vm-windows-utm-air-m5 'cmd /c "echo OK & query user"'
# Debe devolver: eldo.loguzzo / console / 1 / Activo
# Reemplazar host para verificar mini-m2 / surface-pro-x.
```

### 8.3 Workflow A — Test only (sin build remoto)

El más usado. Tu dev box (macOS/Linux) hace cross-build (§7); el ZIP se
valida en la VM Windows vía SSH. Tiempo total: ~3 min smoke + el tiempo
del cross-build.

```bash
# Después de un cross-build local:
ZIP=/Users/eldo.loguzzo/work/Proyectos/PayBench-QA-win-x64-$(date +%Y%m%d).zip
VM=vm-windows-utm-air-m5
VM_DIR='C:\Users\eldo.loguzzo\PayBench-QA-win-x64-'$(date +%Y%m%d)

ssh $VM 'cmd /c "rmdir /s /q '$VM_DIR' 2>nul & del /q '$VM_DIR'.zip 2>nul"'
scp "$ZIP" "$VM:$VM_DIR.zip"
ssh $VM 'cmd /c "cd /d C:\Users\eldo.loguzzo && tar -xf '$VM_DIR'.zip"'
ssh $VM 'cmd /c "cd /d '$VM_DIR' && del paybench-startup.log 2>nul & smoke-windows-vm.bat"'
```

Salida esperada: `RESUMEN: 6 PASS / 0 FAIL / 2 SKIP / 8 total`.

> Detalle clave: el smoke `.bat` usa `schtasks /create /it /ru <user>`
> para los GUI tests (Electron, Tauri). Sin esto, los procesos lanzados
> via SSH heredan Session 0 (sshd) y Tauri/WebView2 cuelga. Ver
> [QA-SMOKE-TEST.md §4.5.6bis](QA-SMOKE-TEST.md) (decision record).

### 8.4 Workflow B — Build remoto en Windows nativo via SSH

Cuando necesitás un build 100% nativo Windows (sin cross-compile):

```bash
# Una sola vez: clonar el repo en la VM
ssh vm-windows-utm-air-m5 'cmd /c "git clone https://github.com/ASAP-TECHNOLOGY/POS-Simulator C:\repo\paybench && cd /d C:\repo\paybench && npm install"'

# Cada build:
ssh vm-windows-utm-air-m5 'cmd /c "cd /d C:\repo\paybench && git pull && npm run dist:qa:win:rebuild-all"'

# Bajar el ZIP resultante
scp 'vm-windows-utm-air-m5:C:\Users\eldo.loguzzo\work\Proyectos\PayBench-QA-win-x64-*.zip' /Users/eldo.loguzzo/work/Proyectos/
```

Tiempo típico: ~25 min (Tauri Docker en la VM es el cuello de botella —
si Docker no está disponible en la VM Windows, Tauri se compila con la
toolchain MSVC nativa en ~5 min, más rápido).

**Cuándo conviene B vs A**:
- Necesitás binarios `*-win-arm64.exe` (no en cross-build, requiere
  máquina ARM64 nativa — la VM Win11 ARM64 lo es).
- Probaste smoke en VM y querés re-buildear sin pasar por tu host
  macOS/Linux.
- Validás un cambio que solo se manifiesta en MSVC nativo (vs xwin en
  Docker).

### 8.5 ⚠️ Gotchas — Session 0 + tasklist truncate

Ya documentados en QA-SMOKE-TEST.md §4.5.5 y §4.5.6. Resumen:

- **Session 0**: procesos via SSH heredan la sesión del sshd (Session 0
  = Services, sin desktop). Apps GUI cuelgan. Fix: `schtasks /it`.
- **tasklist truncate**: el output default trunca nombres a 25 chars.
  Fix: `tasklist /fo csv /nh`.

Ambos fixes ya están aplicados en `scripts/smoke-windows-vm.bat`.

---

## 9. Troubleshooting

### `is not a valid Win32 application`

You ran a Windows packager from macOS/Linux without swapping native
modules. Use the `:cross` variants from Section 7, or run on Windows.

### `LoadLibraryExW failed`

Same root cause as above — wrong-arch native module embedded.

### `cannot find module ... build\Release\node_sqlite3.node`

The packaging method does not embed sqlite3 (Bun is the canonical case)
and the runtime can't find the file next to the .exe. Use the portable
QA bundle (Section 5) instead of shipping the bare .exe, or copy
`build\Release\node_sqlite3.node` next to the .exe manually.

### `npm install` re-downloads Mach-O sqlite3 after a swap

The `.swap-backup/` was wiped. Run `npm rebuild sqlite3 better-sqlite3`
to fetch the host-platform prebuilds again.

### Electron portable says "PayBench backend timeout"

Backend child exited or never bound to port 9095. Check `stderr` of the
.exe (run from a `cmd.exe` to see the `[backend]` lines), or check the
Windows Firewall isn't blocking localhost:9095.

### Tauri build complains about missing WebView2

Install via https://developer.microsoft.com/microsoft-edge/webview2/ —
the runtime is preinstalled on Win11 / Win10 ≥ 21H2 but not on older
builds.
