# Platform Strategies — Why each runtime uses a different SQLite / SerialPort

> 📘 **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: maintainers, QA leads, anyone debugging a "but it works on Node, why
> not on Bun?" issue.
> Last updated: 2026-05-07.

PayBench targets eight runtime/packaging combinations and three database
abstractions plus one optional USB serial transport. Not every combination
uses the same underlying driver: some runtimes refuse to load `better-sqlite3`,
mobile runtimes refuse to load native `.node` addons at all, and Apple
prohibits USB host on iOS. This document explains the constraints and the
strategy chosen for each.

## TL;DR

| Concern | Default desktop | Bun | Deno | Android | iOS |
|---|---|---|---|---|---|
| **SQLite (sync API)** | `better-sqlite3` native | `bun:sqlite` shim | `node:sqlite` shim | `sql.js` asm.js shim **or** Kotlin Bridge | `sql.js` asm.js shim **or** Swift Bridge |
| **SQLite (async, Knex)** | `sqlite3` (N-API) | `sqlite3` works | `sqlite3` works | same shim handles both | same shim handles both |
| **USB SerialPort** | `serialport` native | `serialport` native | `serialport` native | Kotlin `UsbSerialBridgePlugin` | ❌ blocked by Apple |
| **HTTP backend** | NestJS / Hono / Fastify / Express | all four | all four | **Hono only** | **Hono only** |

## SQLite — driver choice per runtime

The application code uses three DB abstractions: **Knex**, **Kysely**, and
**TypeORM**. Knex is async (callback) and runs on top of the `sqlite3` npm
package. Kysely (`BetterSqlite3Dialect`) and TypeORM (`type: 'better-sqlite3'`)
both want the **synchronous** `better-sqlite3` package. That single dependency
has different stories per runtime.

### Node desktop (and PKG)

`better-sqlite3` loads natively. PKG embeds Node 24.13, so the binding is
rebuilt for that ABI by `npm run rebuild:better-sqlite3:for-pkg` (chained
in `compile:pkg:current`).

### Bun

Bun 1.3.x **explicitly rejects** `better-sqlite3`:

```
Error: 'better-sqlite3' is not yet supported in Bun.
```

Bun ships its own `bun:sqlite` (sync, almost the same API as better-sqlite3),
so we shim the require at runtime:

- `src/core/database/better-sqlite3-bun-shim.js` wraps `bun:sqlite` to expose
  the better-sqlite3 surface (Database, Statement.run/get/all/iterate/
  pluck/raw, db.exec/pragma/transaction).
- `src/core/database/sqlite-runtime-loader.ts` installs a
  `Module._resolveFilename` interceptor that reroutes `require('better-sqlite3')`
  to the shim **only when** running under Bun.
- One subtle: `Statement.reader` must reflect SQL kind (true for SELECT,
  false for INSERT). TypeORM's `BetterSqlite3QueryRunner` dispatches on this
  property — getting it wrong silently turns INSERTs into 0-row queries.

### Deno

Deno emulates Node's libuv but **hangs indefinitely** in `new Database()`
when loading `better-sqlite3`'s native binding (verified with 65 s of waiting,
reproducible standalone). The constructor never returns.

The Deno fix uses Node 22+'s built-in `node:sqlite` (`DatabaseSync` class)
which Deno fully supports through node compat:

- `src/core/database/better-sqlite3-deno-shim.js` wraps `DatabaseSync` /
  `StatementSync`, mirroring the Bun shim layout.
- `node:sqlite` treats a single Array argument as a named-parameters object
  (`Object.keys([1,2,3])` returns `["0","1","2"]`). The shim's `normalizeParams`
  spreads single-array arguments back into positional before calling node:sqlite,
  otherwise Kysely / TypeORM hit `Error: Unknown named parameter '0'`.

### Why does Knex still work everywhere?

Knex uses `sqlite3` (npm), which is **N-API** (ABI-stable) and async. N-API is
designed to survive ABI changes; Bun and Deno both load it without trouble.
`better-sqlite3` is **raw V8** with sync C calls — that is the part both Bun
and Deno cannot accept yet.

### Android

`bootstrap.js` injects a `process.dlopen` interceptor that **rejects every
native `.node` file** (line ~194). The reason: the embedded libnode.so on
NodeMobile is built without ABI compatibility for typical npm prebuilds.
Loading e.g. `better-sqlite3.node` would crash the process.

Three strategies coexist, selected via `SIMPOS_SQLITE_STRATEGY` env var:

1. **`wasm`** *(default)* — `sql.js` asm.js shim
   ([better-sqlite3-shim.js](../android-app/nodejs-project/better-sqlite3-shim.js)).
   Pure JavaScript SQLite engine. Works on every Android device, no plugin
   registration required. Slower than native (asm.js → V8 interpreter), but
   adequate for typical PayBench flows.
2. **`bridge`** — Kotlin `SqliteBridgePlugin` (`android.database.sqlite`)
   exposed over Capacitor channel, consumed by
   [sqlite-bridge-shim.js](../android-app/nodejs-project/sqlite-bridge-shim.js).
   ~5–10× faster than wasm for typical workloads. Already wired:
   `MainActivity.java:20` registers the plugin.
3. **`native`** — direct `dlopen` of `libsqlite3.so` from `/system/lib`. Only
   works on a custom NodeMobile build that whitelists this path. Disabled by
   default; QA does not normally use it.

### iOS / iPadOS

Same dlopen restriction as Android plus Apple's `--jitless` requirement
(no V8 JIT) — V8 runs the asm.js shim slower than on Android.

Two strategies, mirroring Android (chosen via the same `SIMPOS_SQLITE_STRATEGY`
env var, set at build time):

1. **`asmjs`** *(default)* — `sql.js` asm.js shim. Same JS file as Android.
   Works on every iPhone/iPad without code-signing changes. Slow in --jitless
   but functional.
2. **`bridge`** *(opt-in)* — Swift `SqliteBridgePlugin.swift` linked against
   the system `libsqlite3` (via `import SQLite3`), exposed over the same
   Capacitor channel that Android uses. The JS shim
   [sqlite-bridge-shim.js](../ios-app/nodejs-project/sqlite-bridge-shim.js)
   is **the same file as Android's**, byte-for-byte — the channel protocol
   is platform-agnostic.

**iOS Bridge — when to use it:** anytime the workload is read- or
write-intensive. asm.js works fine for sporadic SALE → INSERT, but a QA
session with thousands of test transactions, large `transaction-history`
GETs, or stress tests on Knex/Kysely will benefit dramatically from the
bridge.

**iOS Bridge — pending wire-up:** the Swift plugin is feature-complete
(open / exec / run / get / all / close, prepared statements, parameter
binding for null/string/int/double/bool/blob, BEGIN/COMMIT/ROLLBACK
transactions). What is not done yet:

- Add `ios-app/ios/App/App/sqlite/SqliteBridgePlugin.swift` to the Xcode
  target's *Compile Sources* phase (a `project.pbxproj` edit).
- In `AppDelegate.swift`, after Capacitor bridge initialization:
  `bridge?.registerPluginInstance(SqliteBridgePlugin())`.
- Tag `<key>NSCameraUsageDescription</key>` is *not* required, but if
  added later for other features, ensure the SQLite plugin still loads.

These are 5 minutes of work on a Mac with Xcode. Until done, `bridge`
strategy on iOS will fail silently (the JS shim sends `sqlite:cmd` events
that nobody handles → its pending promises time out with a clear error).

## SerialPort — same source, different transport

The application's `device.service.ts` instantiates one of three transports
based on `connection.type` and the `--android` runtime flag:

- `serial` (default desktop) → `SerialTransport` → `serialport` npm package.
- `tcp` → `TcpTransport` → Node's `node:net`.
- `mock` → `MockTransport` → `@serialport/binding-mock`. *Added 2026-05-06.
  Lets QA exercise the device flow without a physical PINPAD.*
- `serial` + `--android` → `AndroidBridgeTransport` → `bridge.channel`
  delegating to `UsbSerialBridgePlugin.kt`. *Already wired, registered in
  MainActivity.java:19.* Uses the Android USB Host API to talk to PINPADs
  over CDC ACM, no native .node addon needed.
- iOS — **no transport available**. Apple's MFi program prohibits USB host
  on third-party apps. Documented in `docs/DESIGN-TIMEOUT-RECOVERY-DEVICE.md`
  §13. PayBench on iOS is functional for online flows (HTTP-only) and the
  TCP transport (talking to a network PINPAD over WiFi).

## HTTP backend — why mobile is Hono-only

NestJS depends on `reflect-metadata` (decorator metadata reading) and runs
a 200+ provider DI container at bootstrap. On NodeMobile this takes 10–30 s
on Android (V8 JIT enabled in the alzhuravlev fork) and is unviable on iOS
(JIT prohibited → DI scan in interpreter mode is so slow the OS kills the
app). Hono has zero reflect-metadata, zero DI, and starts in 1–3 s on the
same hardware.

The codebase uses **shared core services** (`src/core/`) — both NestJS and
Hono adapters consume the same `SessionsService`, `TransactionsService`,
etc. The 13 API endpoints are identical between adapters. Switching backend
on mobile is just changing one `require()` in the bootstrap script:

- `android-app/nodejs-project/bootstrap.js`: loads
  `dist/src/adapters/hono/main.js` (since 2026-05-06).
- `ios-app/nodejs-project/bootstrap-ios.js`: same Hono adapter.

Desktop runtimes (Node, PKG, NCC, SEA, Bun, Deno, Tauri) keep all four
backends (NestJS, Hono, Express, Fastify) selectable for QA matrix coverage.

## Decision-record summary

| Constraint | Source | Picked because |
|---|---|---|
| Bun rejects better-sqlite3 | Runtime error message | bun:sqlite shim (sync API match) |
| Deno hangs in better-sqlite3 ctor | libuv emul incompatibility | node:sqlite shim (Node 22+ built-in, sync) |
| Android dlopen blocked | Bootstrap interceptor | sql.js asm.js (default) + Kotlin bridge (opt-in) |
| iOS dlopen blocked + JIT prohibited | Apple App Store policy | sql.js asm.js (default) + Swift bridge (opt-in) |
| iOS USB host blocked | Apple MFi policy | No serial on iOS — TCP transport instead |
| NestJS DI scan slow on NodeMobile | Profiling on real device | Hono on mobile only |
| PKG can't include host's better-sqlite3 ABI | yao-pkg embeds Node 24.13 | `rebuild:better-sqlite3:for-pkg` script |
| SEA's webpack bundle drops `.node` files | postject limitations | NATIVE_MODULES list patched in sea-build.mjs |
| NCC bundle's webpack-mode breaks node-gyp-build path lookup | Known upstream | `patch-ncc-native.mjs` copies prebuilds + node.napi.node alias |
| Path-to-regexp 8.x changed wildcard syntax | Express 5.x update | `app.options('/*splat', ...)` (was `'*'`) |

## Where these decisions live in the source

- Runtime detection + shim install: [src/core/database/sqlite-runtime-loader.ts](../src/core/database/sqlite-runtime-loader.ts)
- Bun shim: [src/core/database/better-sqlite3-bun-shim.js](../src/core/database/better-sqlite3-bun-shim.js)
- Deno shim: [src/core/database/better-sqlite3-deno-shim.js](../src/core/database/better-sqlite3-deno-shim.js)
- Android sql.js shim: [android-app/nodejs-project/better-sqlite3-shim.js](../android-app/nodejs-project/better-sqlite3-shim.js)
- Android Bridge shim (JS): [android-app/nodejs-project/sqlite-bridge-shim.js](../android-app/nodejs-project/sqlite-bridge-shim.js)
- Android Bridge plugin (Kotlin): [android-app/.../SqliteBridgePlugin.kt](../android-app/android/app/src/main/java/com/pos/simulator/sqlite/SqliteBridgePlugin.kt)
- Android USB Bridge: [android-app/.../UsbSerialBridgePlugin.kt](../android-app/android/app/src/main/java/com/pos/simulator/usb/UsbSerialBridgePlugin.kt)
- iOS Bridge plugin (Swift): [ios-app/.../SqliteBridgePlugin.swift](../ios-app/ios/App/App/sqlite/SqliteBridgePlugin.swift)
- Mobile bootstrap dispatcher: [android-app/nodejs-project/bootstrap.js](../android-app/nodejs-project/bootstrap.js) and [ios-app/nodejs-project/bootstrap-ios.js](../ios-app/nodejs-project/bootstrap-ios.js)
- Mock SerialPort transport: [src/core/services/device-transport.ts:585+](../src/core/services/device-transport.ts) (`MockTransport`)
- AndroidBridgeTransport: [src/core/services/android-bridge-transport.ts](../src/core/services/android-bridge-transport.ts)

## Cross-compiling to Windows from macOS/Linux

The same `.exe` artifact has to come out of CI runners and out of a dev's
macOS/Linux laptop. The two paths diverge for **Tauri** specifically.

### Standalone runtimes (PKG / NCC / Bun / Deno / Electron)

These pull in `sqlite3` and `better-sqlite3` from `node_modules/`. `npm install`
on macOS fetches **Mach-O arm64** prebuilds, which the Windows packagers
silently embed → the `.exe` crashes on Windows with `is not a valid Win32
application` or `LoadLibraryExW failed`.

**Strategy** (verified 2026-05-13):

- Commit Windows prebuilds in `prebuilds-cache/win32-x64/`.
- Before packaging, swap them into `node_modules/{sqlite3,better-sqlite3}/build/Release/` via `scripts/swap-native-modules.mjs`.
- Build.
- Restore the host's macOS prebuilds via `node scripts/swap-native-modules.mjs restore` so `npm start` keeps working.

Wrapped in `compile:{pkg,ncc,bun,deno}:win-x64:cross` + `electron:dist:win:cross`. No Docker required.

Why not just `electron-builder --x64 --arm64 --win` from macOS without the
swap? Because `electron-builder` defaults to `npmRebuild: true` which would
rebuild native modules for the **host** platform. We set `npmRebuild: false`
in `electron-app/package.json` and rely on the swap.

### Tauri (`x86_64-pc-windows-msvc`)

Tauri compiles Rust to the **MSVC ABI**. `cc-rs` (transitive via `tauri-build` →
`embed-resource`) explicitly **rejects GNU compilers** for MSVC targets with
the warning `GNU compiler is not supported for this target`. So neither
arm64-host gcc nor mingw-w64 GCC work — even though mingw is the textbook
Linux → Windows cross-compile path.

**Strategy** (verified 2026-05-13):

- Bake the whole MSVC toolchain into a reusable Docker image: `paybench/tauri-windows-builder:latest`.
  - `xwin --accept-license --arch x86_64 splat --output /xwin` — fetches Microsoft SDK + CRT.
  - Wrappers `/usr/local/bin/clang-cl-xwin` (`clang --driver-mode=cl /imsvc /xwin/{crt,sdk}/include/...`) and `/usr/local/bin/lld-link-xwin` (`lld-link /libpath:/xwin/{crt,sdk}/lib/x86_64/...`).
  - Cargo `[env]` wiring `CC_x86_64_pc_windows_msvc=clang-cl-xwin`, `AR=llvm-lib`, `RC=llvm-rc`. Written to `/usr/local/cargo/config.toml` (not `$HOME/.cargo/` — `CARGO_HOME=/usr/local/cargo` in the rust base image overrides it).
  - `mingw-w64` is still installed for `windres` because some Rust crates ask for it by name even though we use llvm-rc for the actual MSVC resource compile.
- `docker run --rm -v repo:/workspace paybench/tauri-windows-builder:latest cargo tauri build --target x86_64-pc-windows-msvc --bundles nsis`.

Wrapped in `npm run tauri:build:win:docker` (which also pre-builds the NCC sidecar via `cross:swap:win-x64`). No Wine needed for the build — the `.rc` resource is compiled by `llvm-rc`, the `.exe` is linked by `lld-link`, and the NSIS installer is built by Linux `makensis`.

The image is **arch-portable** at the host level (linux/arm64 on Apple Silicon, linux/amd64 elsewhere); target is fixed `x86_64-pc-windows-msvc`. `docker save | gzip` produces ~1.5-2 GB transportable to other hosts.

Why not `cargo-xwin`? It wraps `xwin` + cargo into a single `cargo xwin build` subcommand, but doesn't compose cleanly with `cargo tauri build`. The hand-rolled config in the Dockerfile delivers the same env wiring with full visibility.

### What does NOT cross-compile

- **SEA** — copies the host's `node` binary; output is `mach-o` on macOS even when named `*-win-x64.exe`. Must be built on Windows.
- **Bun standalone on Windows arm64** — Bun's compiler does not target windows-arm64 yet.
- **Tauri arm64** — would need a parallel xwin splat (`--arch aarch64`) and a wrapper variant.

## See also

- [docs/CROSS-BUILD.md](CROSS-BUILD.md) — full cross-build runbook + Wine smoke-test notes
- [docs/WINDOWS-BUILD-GUIDE.md](WINDOWS-BUILD-GUIDE.md) — native Windows build path
- [docs/ANDROID-BUILD-GUIDE.md](ANDROID-BUILD-GUIDE.md) §11 — Kotlin bridge architecture detail
- [docs/IOS-BUILD-GUIDE.md](IOS-BUILD-GUIDE.md) — iOS build steps
- [docs/DESIGN-TIMEOUT-RECOVERY-DEVICE.md](DESIGN-TIMEOUT-RECOVERY-DEVICE.md) §13 — Apple platform USB analysis
- [CHANGELOG.md](../CHANGELOG.md) — entries from 2026-05-06 / 2026-05-07 trace each strategy decision to its commit
