@ohtaman/washi 0.8.2 → 0.9.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +3 -0
  2. package/dist/browser/solvers/{highs-__vite-browser-external-Dn-83hnF.js → highs-__vite-browser-external-xcxOpLMD.js} +1 -1
  3. package/dist/browser/solvers/{highs-browser-runtime-0Bgq5ksG.js → highs-browser-runtime-ccRmE4qj.js} +1 -1
  4. package/dist/browser/solvers/highs-inline.js +51 -0
  5. package/dist/{lib/solvers/loader-CDpPXN_F.js → browser/solvers/highs-loader-Csn3-0tq.js} +241 -149
  6. package/dist/browser/solvers/highs-worker.js +17 -16
  7. package/dist/browser/solvers/highs.js +295 -255
  8. package/dist/browser/solvers/pumpkin-inline.js +51 -0
  9. package/dist/{lib/solvers/loader-Ow74Fa1B.js → browser/solvers/pumpkin-loader-BI3n3dWO.js} +145 -55
  10. package/dist/browser/solvers/pumpkin-worker.js +24 -23
  11. package/dist/browser/solvers/pumpkin.js +307 -288
  12. package/dist/browser/washi.min.js +4 -4
  13. package/dist/lib/solvers/embedded-wasm-CSFlLV5N.js +49 -0
  14. package/dist/lib/solvers/highs-node-runtime.js +1 -7
  15. package/dist/lib/solvers/highs-worker.js +19 -17
  16. package/dist/lib/solvers/highs.js +153 -112
  17. package/dist/{browser/solvers/highs-loader-BLY3wzDH.js → lib/solvers/loader-DCtyxsfF.js} +56 -36
  18. package/dist/{browser/solvers/pumpkin-loader-CvdaKxf4.js → lib/solvers/loader-b5PNpCmX.js} +58 -33
  19. package/dist/lib/solvers/pumpkin-worker.js +25 -23
  20. package/dist/lib/solvers/pumpkin.js +212 -192
  21. package/dist/types/modeler/solvers/embedded-wasm.d.ts +36 -0
  22. package/dist/types/modeler/solvers/embedded-wasm.d.ts.map +1 -0
  23. package/dist/types/modeler/solvers/highs/loader.d.ts.map +1 -1
  24. package/dist/types/modeler/solvers/highs/node-runtime.d.ts.map +1 -1
  25. package/dist/types/modeler/solvers/highs/worker-client.d.ts.map +1 -1
  26. package/dist/types/modeler/solvers/inline-pack.d.ts +6 -0
  27. package/dist/types/modeler/solvers/inline-pack.d.ts.map +1 -0
  28. package/dist/types/modeler/solvers/pumpkin/loader.d.ts +1 -1
  29. package/dist/types/modeler/solvers/pumpkin/loader.d.ts.map +1 -1
  30. package/dist/types/modeler/solvers/pumpkin/solver.d.ts.map +1 -1
  31. package/dist/types/modeler/solvers/pumpkin/worker-client.d.ts.map +1 -1
  32. package/dist/types/modeler/solvers/pumpkin/worker.d.ts +1 -0
  33. package/dist/types/modeler/solvers/pumpkin/worker.d.ts.map +1 -1
  34. package/docs/getting-started/ai-agents.md +55 -1
  35. package/docs/getting-started/runtimes.md +46 -1
  36. package/docs/solvers/highs.md +2 -0
  37. package/docs/solvers/pumpkin.md +2 -0
  38. package/llms-full.txt +105 -2
  39. package/llms.txt +55 -1
  40. package/package.json +12 -1
  41. package/skills/washi/SKILL.md +66 -2
  42. package/skills/washi-single-html/SKILL.md +335 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ohtaman/washi",
3
- "version": "0.8.2",
3
+ "version": "0.9.0-rc.1",
4
4
  "description": "WaSHI: TypeScript & JavaScript algebraic modeler for Mathematical Optimization & Constraint Programming (LP, MILP, QP, CP, SMT) powered by WebAssembly (HiGHS, Pumpkin, Z3, GLPK)",
5
5
  "type": "module",
6
6
  "main": "./dist/lib/washi.js",
@@ -47,11 +47,21 @@
47
47
  "import": "./dist/browser/solvers/highs.js",
48
48
  "default": "./dist/browser/solvers/highs.js"
49
49
  },
50
+ "./browser/solvers/highs-inline": {
51
+ "types": "./dist/types/modeler/solvers/inline-pack.d.ts",
52
+ "import": "./dist/browser/solvers/highs-inline.js",
53
+ "default": "./dist/browser/solvers/highs-inline.js"
54
+ },
50
55
  "./browser/solvers/pumpkin": {
51
56
  "types": "./dist/types/modeler/solvers/pumpkin/index.d.ts",
52
57
  "import": "./dist/browser/solvers/pumpkin.js",
53
58
  "default": "./dist/browser/solvers/pumpkin.js"
54
59
  },
60
+ "./browser/solvers/pumpkin-inline": {
61
+ "types": "./dist/types/modeler/solvers/inline-pack.d.ts",
62
+ "import": "./dist/browser/solvers/pumpkin-inline.js",
63
+ "default": "./dist/browser/solvers/pumpkin-inline.js"
64
+ },
55
65
  "./browser/solvers/z3": {
56
66
  "types": "./dist/types/modeler/solvers/z3/index.d.ts",
57
67
  "import": "./dist/browser/solvers/z3.js",
@@ -75,6 +85,7 @@
75
85
  "docs/solvers",
76
86
  "docs/examples",
77
87
  "skills/washi/SKILL.md",
88
+ "skills/washi-single-html/SKILL.md",
78
89
  "llms.txt",
79
90
  "llms-full.txt",
80
91
  "README.md",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: washi
3
- description: Formulate, inspect, solve, and verify mathematical optimization (LP, MILP/MIP, convex QP, CP/LCG) and SMT satisfiability or unsat-core models in TypeScript and JavaScript using @ohtaman/washi (HiGHS, Pumpkin, Z3, GLPK) for shift scheduling, timetabling, resource allocation, bin packing, routing, portfolio optimization, and rule conflict diagnosis.
3
+ description: Formulate, inspect, solve, and verify mathematical optimization (LP, MILP/MIP, convex QP, CP/LCG, column generation, Benders decomposition) and SMT satisfiability or unsat-core models in TypeScript and JavaScript using @ohtaman/washi (HiGHS, Pumpkin, Z3, GLPK) for shift scheduling, timetabling, resource allocation, bin packing, routing, portfolio optimization, and rule conflict diagnosis.
4
4
  ---
5
5
 
6
6
  # WaSHI Modeling & Verification Skill
@@ -20,11 +20,14 @@ Select the solver engine and execution method that match the problem class:
20
20
  | **SMT Propositional Logic** (`BoolVar`, `and`, `or`, `not`, `implies`, `xor`) | **HiGHS** (auto 0-1 MIP), **Pumpkin** (bounded int), or **Z3** (native SMT incl. `Continuous`) | Bundled for HiGHS & Pumpkin; `npm install z3-solver` + `import "@ohtaman/washi/solvers/z3"` for Z3 | `await m.solve()` or `await m.check()` |
21
21
  | **Infeasibility / Conflict Diagnosis** (`conflicts` / `unsatCore`) | **HiGHS** (relaxation `conflicts`), **Pumpkin** (bounded int/bool `unsatCore`), or **Z3** (`unsatCore`) | Bundled for HiGHS & Pumpkin; `import "@ohtaman/washi/solvers/z3"` for Z3 | `await m.check()` |
22
22
  | **LP / MIP with GLPK** (GPL-3.0; no QP, `initialValue`, or `useWorker: true`) | **GLPK** plugin | `npm install glpk.js` + `import "@ohtaman/washi/solvers/glpk"` | `await m.solve({ solver: "glpk" })` |
23
+ | **Decomposition** (`solveColumnGeneration`, `solveBenders`, `m.relax()`) | **HiGHS** (default) or **GLPK** (required for LP duals / `relax: true` in `solveColumnGeneration`, `m.relax()`, and auto-cut `sub.link()`; `Pumpkin` and `Z3` lack LP duals) | Bundled for HiGHS; `import "@ohtaman/washi/solvers/glpk"` for GLPK | `await master.solveColumnGeneration(...)` / `await master.solveBenders(...)` |
23
24
 
24
25
  - **Browser runtime notes**:
25
26
  - **HiGHS** and **Pumpkin** load bundled `.wasm` and Worker assets relative to the bundle (no external CDN fallback; `useWorker: false` by default on opaque origins such as `file://`).
26
27
  - **HiGHS**, **Pumpkin**, and **GLPK** all run without `COOP`/`COEP` headers (**GLPK** is an optional peer dependency that rejects `useWorker: true`).
27
28
  - **Z3** uses `SharedArrayBuffer` pthreads and requires `window.isSecureContext === true` and `window.crossOriginIsolated === true` (`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`).
29
+ - **Single-file / CSP-restricted pages (blocked `fetch()`)**: Environments such as published Claude.ai artifacts or restricted HTML previews allow CDN scripts (`script-src`) while blocking `fetch()` (`connect-src 'none'`). Load the zero-build self-registering CDN inline WASM packs (`solvers/highs-inline.js` / `solvers/pumpkin-inline.js` — usable in both ESM and classic `<script>`) before the first `solve()` / `check()` call (see Recipe 5 below).
30
+ - **Single-file offline HTML + npm packages (`file://`)**: To bundle `@ohtaman/washi` (HiGHS and/or Pumpkin) alongside arbitrary third-party npm packages (React, Chart.js, KaTeX, Tailwind) into one zero-network, double-clickable offline `file://` HTML file using Vite + `vite-plugin-singlefile` + gzipped WASM, follow the **`washi-single-html`** skill (`skills/washi-single-html/SKILL.md`).
28
31
 
29
32
  ---
30
33
 
@@ -50,6 +53,21 @@ Select the solver engine and execution method that match the problem class:
50
53
  - Named constraints: Register every constraint with a descriptive name via `const limit = m.constraint(c, "resource_limit")` (returns the registered `Constraint` / `BoolExpr`, or an array for batch inputs). Names are essential for LP inspection and conflict diagnosis (`conflicts` / `unsatCore`).
51
54
  - Indicator constraints: Register conditional constraints via `m.indicator(binVar, c, { activeValue: 1, name: "cap_when_open" })`. When `options.M` is omitted, HiGHS/GLPK and `toLpString()` derive a tight Big-M from finite bounds, while Pumpkin lowers natively via `implied_by` and Z3 via `ctx.Implies`.
52
55
 
56
+ ### Decomposition API Contracts (Column Generation & Benders)
57
+
58
+ For full examples, see [`docs/guide/decomposition.md`](https://github.com/ohtaman/washi/blob/main/docs/guide/decomposition.md) (`node_modules/@ohtaman/washi/docs/guide/decomposition.md`). `solveColumnGeneration()`, `m.relax()`, and `solveBenders()` auto-cut `sub.link(...)` mode require an LP-dual solver (**HiGHS** or **GLPK**; `Pumpkin` and `Z3` lack LP duals); manual `BendersCut` mode only calls `master.solve()`. Both helpers are also exported standalone.
59
+
60
+ - **Column Generation**: `await master.solveColumnGeneration({ pricing, finalizeAsMIP?, reducedCostTolerance?, maxIterations?, solver?, solverOptions?, onIteration? })`
61
+ - `pricing` receives `{ duals, getDual, iteration, master, masterSolution, reducedCostTolerance }` and returns `ColumnProposal | ColumnProposal[] | null` (`{ cost, coefficients, type?, lb?, ub?, name?, reducedCost?, meta? }`).
62
+ - Reduced cost (`cost - sum(pi_i * a_i)`) is checked automatically when `proposal.reducedCost` is omitted; `proposal.type` defaults to `"Continuous"`, so pass `type: "Integer"` or `"Binary"` for integer columns.
63
+ - Initial RMP LP relaxation must be feasible and bounded (no Phase-I artificials); `finalizeAsMIP: true` (default) runs a root-node Price-and-Branch heuristic rather than exact Branch-and-Price.
64
+ - **Benders Decomposition**: `await master.solveBenders({ subproblem, theta?, gapTolerance?, maxIterations?, solver?, solverOptions?, onIteration? })`
65
+ - `subproblem` receives `{ iteration, masterValues, getMasterValue, masterObjective, lowerBound, upperBound, master }` and returns a continuous LP `Model` with `sub.link(constraint)` or manual `BendersCut | BendersCut[] | null` (`{ kind: "optimality" | "feasibility", constraint, name?, subproblemObjective? }`).
66
+ - Auto-cut `sub.link(...)` mode generates optimality cuts only and throws if the LP subproblem is infeasible; add master feasibility guards or return manual `kind: "feasibility"` cuts.
67
+ - Auto-`theta` assumes a `Minimize` master with `lb: 0` (injecting `__benders_theta` unless `theta` exists); for `Maximize` or negative subproblem costs, declare `theta` on `master`, add it to `master.objective(...)`, and pass `{ theta }`.
68
+ - Manual `BendersCut.subproblemObjective` expects **Stage-1 direct cost (excluding `theta`) + Stage-2 cost**, not Stage-2 subproblem cost alone.
69
+ - **Low-level primitives**: `await m.relax()` (LP relaxation for duals), `c.dual` (or `m.solution?.duals[name]`), `m.column({ cost, coefficients, type?, lb?, ub?, name? })`, and `c.addTerm(v, coeff)` / `c.setTerm(v, coeff)`.
70
+
53
71
  ---
54
72
 
55
73
  ## 3. Model Inspection (`toLpString`)
@@ -70,7 +88,7 @@ Never report a model solution as final without executing the verification step:
70
88
  - Verify `status === "Optimal"` (or `status === "Feasible"` / `m.hasPrimalSolution === true` when solver limits apply).
71
89
  - Call `const report = m.verify()` and assert `report.valid === true`.
72
90
  - If `report.valid === false`, inspect `report.violations`, `report.missingVariables`, `report.uncheckedConstraints`, and `report.maxViolation`.
73
- - Note: `m.verify()` independently checks variable finiteness, variable bounds (`lb`/`ub`), integrality (`Integer`, `Binary`, `BoolVar`), linear constraint residuals, and logical constraints. It does **not** recompute `m.objectiveValue` or verify natural-language problem coverage.
91
+ - Note: `m.verify()` independently checks variable finiteness, variable bounds (`lb`/`ub`), integrality (`Integer`, `Binary`, `BoolVar`), linear constraint residuals, and logical constraints. It does **not** recompute `m.objectiveValue` or verify natural-language problem coverage. On decomposed models, `master.verify()` checks only the master model's constraints, bounds, and integrality; verify end-to-end invariants outside the master (e.g., TSP single-tour connectivity or full subproblem demand satisfaction) with explicit domain assertions.
74
92
  2. **When a model is infeasible (`"Infeasible"` or `"Unsat"`)**:
75
93
  - Run `const res = await m.check()` for built-in HiGHS diagnosis (single-solve elastic slack relaxation), `await m.check({ solver: "pumpkin" })` for bounded integer/boolean `unsatCore`, or `await m.check({ solver: "z3" })` for exact SMT `unsatCore` including `Continuous`/fractional constraints.
76
94
  - When `res.status === "Unsat"`, inspect `res.conflicts` (also stored on `m.conflicts`). On Z3 and Pumpkin, both `res.unsatCore` and `res.conflicts` report a contradictory subset of constraints.
@@ -245,6 +263,52 @@ export async function solveAndDiagnoseWithPumpkin() {
245
263
  }
246
264
  ```
247
265
 
266
+ ### Recipe 5: Single-File HTML & CSP-Restricted Environments (No `fetch`)
267
+
268
+ Some hosted single-file environments (for example, published Claude.ai artifacts or restricted HTML previews) allow CDN scripts (`script-src`) while blocking `fetch()` via `connect-src 'none'`. In that setup, default `.wasm` loading fails because HiGHS and Pumpkin fetch their `.wasm` files at startup.
269
+
270
+ Load the self-registering inline WASM packs (`solvers/highs-inline.js` / `@ohtaman/washi/browser/solvers/highs-inline` and `solvers/pumpkin-inline.js` / `@ohtaman/washi/browser/solvers/pumpkin-inline`) **before** the first `solve()`, `check()`, or `warmup*()` call—no manual base64 decoding or binary setters are needed, and the same `*-inline.js` file works in both ESM and classic `<script>` mode:
271
+
272
+ ```html
273
+ <!-- ESM (<script type="module">) -->
274
+ <script type="module">
275
+ import { Model, expr, maximize } from "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/washi.js";
276
+ import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/highs-inline.js";
277
+ import "https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/pumpkin-inline.js";
278
+
279
+ const m = new Model("CspSafeMIP");
280
+ const x = m.integer("x", { lb: 0 });
281
+ const y = m.integer("y", { lb: 0 });
282
+ m.objective(maximize(expr`30 * ${x} + 50 * ${y}`));
283
+ m.constraint(expr`${x} + 2 * ${y} <= 40`, "wood");
284
+ m.constraint(expr`2 * ${x} + ${y} <= 50`, "labor");
285
+ await m.solve(); // Works in both main-thread and Web Worker mode without fetch()
286
+
287
+ const cp = new Model("CspSafeCP", { solver: "pumpkin" });
288
+ const k = cp.integer("k", { lb: 0, ub: 6 });
289
+ cp.objective(maximize(expr`10 * ${k}`));
290
+ await cp.solve(); // Works without fetch() as well
291
+ </script>
292
+
293
+ <!-- Classic <script> (works even with worker-src 'none' when useWorker: false) -->
294
+ <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/washi.min.js"></script>
295
+ <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/highs-inline.js"></script>
296
+ <script src="https://cdn.jsdelivr.net/npm/@ohtaman/washi/dist/browser/solvers/pumpkin-inline.js"></script>
297
+ <script>
298
+ (async () => {
299
+ const { Model, expr, maximize } = Washi;
300
+ const m = new Model("CspSafeClassic");
301
+ const x = m.integer("x", { lb: 0 });
302
+ m.objective(maximize(x));
303
+ m.constraint(expr`${x} <= 10`, "cap");
304
+ await m.solve({ useWorker: false }); // Zero fetch(), zero Blob URLs, zero Workers
305
+ })();
306
+ </script>
307
+ ```
308
+
309
+ - **Initialization & Worker behavior without `fetch()`**: Load `*-inline.js` before the first `solve()`, `check()`, or `warmup*()` (order between core and `*-inline.js` before init does not matter; late registration after first init is ignored to keep main-thread and Worker behavior consistent). In Web Worker mode (`useWorker: true`), WaSHI passes the embedded bytes to the Web Worker via `postMessage` once per Worker instance—no `.wasm` `fetch()` occurs inside the Worker. If `worker-src` blocks `blob:` or Workers, or on opaque origins (`window.origin === "null"`), pass `{ useWorker: false }` (opaque origins fall back to the main thread automatically).
310
+ - **Other solvers**: **GLPK** (`solvers/glpk.js`) already embeds its WASM inline and requires no extra setup (GPL-3.0). **Z3** requires `SharedArrayBuffer` / `COOP`+`COEP` headers and is out of scope for standalone CSP-restricted artifacts.
311
+
248
312
  ---
249
313
 
250
314
  ## 6. Guardrails & Common Pitfalls
@@ -0,0 +1,335 @@
1
+ ---
2
+ name: washi-single-html
3
+ description: This skill should be used when building a single-file, offline-ready HTML web application using @ohtaman/washi (alongside arbitrary third-party npm packages such as React, Chart.js, KaTeX, or Tailwind) that opens directly via file:// with zero network requests and zero extra assets.
4
+ ---
5
+
6
+ # WaSHI Single-File Offline HTML App Skill
7
+
8
+ Build self-contained, single-file `index.html` applications that bundle `@ohtaman/washi` (HiGHS and Pumpkin WASM solvers) together with any third-party npm UI, charting, or math libraries so end users can double-click the file (`file://`) offline with zero local servers, zero external CDN requests, and zero extra asset files.
9
+
10
+ ## Architecture Overview
11
+
12
+ > **When to use `washi-single-html` vs. `*-inline.js`**: Use **`washi-single-html`** when Vite-bundling a zero-network, double-clickable offline `file://` HTML app with gzipped WASM and third-party npm UI libraries (`react`, `katex`, `chart.js`, `tailwindcss`). For zero-build HTML snippets hosted inside CSP-restricted sandboxes (`connect-src 'none'`, such as ChatGPT HTML previews or published Claude.ai artifacts), use WaSHI's CDN `solvers/highs-inline.js` / `solvers/pumpkin-inline.js` packs instead (see `skills/washi/SKILL.md`).
13
+
14
+ A standard `vite-plugin-singlefile` build already inlines JS modules, CSS, web fonts, and images from any npm dependency (`react`, `katex`, `chart.js`, `tailwindcss`, etc.) into one HTML file. WaSHI adds three extra single-file constraints that standard plugins do not handle alone:
15
+
16
+ 1. **Blocked `fetch()` on `file://`**: Browsers block relative `fetch("./highs.wasm")` requests on opaque `file://` origins. Embed compressed WASM inside inert `<script type="text/plain">` tags and hydrate via `FileReader.readAsDataURL()` (`data:application/wasm;base64,...`) passed to `setHighsWasmUrl()` / `setPumpkinWasmUrl()`. Avoid `URL.createObjectURL()` because opaque `file://` origins produce restricted `blob:null/...` URLs.
17
+ 2. **No external Worker scripts**: Intercept WaSHI's internal solver asset and worker-factory modules during bundling so Vite emits zero sidecar `.wasm` or `*-worker.js` files, and always pass `{ useWorker: false }` in `solve()` / `check()` so the same HTML also stays single-file if hosted over `http://` or `https://`.
18
+ 3. **Small file size via gzip**: Raw Base64-encoded `.wasm` in JS swells the HTML past 8.5 MiB and slows script parsing. Gzipping (`level: 9`) into inert `<script type="text/plain" id="washi-wasm-*-gz">` tags shrinks the combined HiGHS + Pumpkin payload to roughly **1.8–2.4 MiB Base64** and decompresses in milliseconds via standard `DecompressionStream("gzip")`.
19
+
20
+ ## Supported Solvers & Hard Exclusions
21
+
22
+ - **Supported**:
23
+ - **HiGHS** (`LP` / `MIP`) via `@ohtaman/washi` and `@ohtaman/washi/solvers/highs` (`highs.wasm`, ~1.36 MiB gzipped)
24
+ - **Pumpkin** (`CP` / `SAT` / `unsatCore`) via `@ohtaman/washi` and `@ohtaman/washi/solvers/pumpkin` (`pumpkin.wasm`, ~398 KiB gzipped)
25
+ - WaSHI decomposition (`benders`, `dantzigWolfe`), `m.verify()`, and arbitrary third-party npm packages
26
+ - **Unsupported in single-file offline HTML**:
27
+ - **Z3** (`@ohtaman/washi/solvers/z3`): Requires `SharedArrayBuffer` pthreads, which demand a secure context (`https://` or `localhost`) and `Cross-Origin-Opener-Policy: same-origin` + `Cross-Origin-Embedder-Policy: require-corp` (`COOP`/`COEP`) response headers. Z3 cannot run over `file://` or in a single headerless HTML file.
28
+ - **GLPK** (`glpk.js`): Optional peer dependency not bundled by default; exclude it in offline single-file builds unless you intentionally install and inline `glpk.js` (`{ useWorker: false }`).
29
+
30
+ ## Project Setup
31
+
32
+ Create a standard Vite app and install `@ohtaman/washi` plus `vite` and `vite-plugin-singlefile`:
33
+
34
+ ```bash
35
+ npm install @ohtaman/washi
36
+ npm install -D vite vite-plugin-singlefile
37
+ # Install any third-party libraries your app needs, e.g.:
38
+ # npm install katex chart.js react react-dom
39
+ ```
40
+
41
+ Include only the WaSHI solvers your app actually uses (`["highs"]`, `["pumpkin"]`, or `["highs", "pumpkin"]`) to keep the output HTML as small as possible.
42
+
43
+ ## Step 1: Add the Vite WaSHI Offline WASM Plugin
44
+
45
+ Save this plugin as `vite-washi-offline.mjs` next to `vite.config.ts`. It prevents Vite from emitting external `.wasm`, `*-worker.js`, `node:*`, or optional Z3/GLPK artifacts, and injects gzipped Base64 WASM payloads into `index.html`.
46
+
47
+ <!-- washi-single-html:vite-plugin -->
48
+ ```js
49
+ import { existsSync, readFileSync } from "node:fs";
50
+ import { createRequire } from "node:module";
51
+ import path from "node:path";
52
+ import { gzipSync } from "node:zlib";
53
+
54
+ const VIRTUAL_PREFIX = "\0washi-single-html:";
55
+
56
+ function resolveDefaultWasmDir() {
57
+ const require = createRequire(import.meta.url);
58
+ return path.dirname(require.resolve("@ohtaman/washi/solvers/highs"));
59
+ }
60
+
61
+ /**
62
+ * Vite plugin that strips external WaSHI WASM/worker/Node/optional-solver
63
+ * emissions and injects gzipped Base64 WASM payloads into index.html.
64
+ *
65
+ * @param {{ wasmDir?: string; solvers?: Array<"highs" | "pumpkin"> }} [options]
66
+ * @returns {import("vite").Plugin}
67
+ */
68
+ export function washiSingleHtmlWasmPlugin(options = {}) {
69
+ const solvers = options.solvers ?? ["highs", "pumpkin"];
70
+ const resolveWasmDir = () => options.wasmDir ?? resolveDefaultWasmDir();
71
+
72
+ return {
73
+ name: "washi-single-html-wasm",
74
+ enforce: "pre",
75
+ resolveId(source, importer) {
76
+ const normalizedImporter = importer?.replaceAll("\\", "/") ?? "";
77
+ const fromSolverDir = (dirName, relBase) =>
78
+ normalizedImporter.includes(`/solvers/${dirName}/`) &&
79
+ new RegExp(`^\\.\\.?\\/${relBase}(?:\\.[jt]s)?$`).test(source);
80
+
81
+ if (source === "./highs-assets.js" || source.endsWith("/highs-assets.js") || fromSolverDir("highs", "assets")) {
82
+ return `${VIRTUAL_PREFIX}highs-assets`;
83
+ }
84
+ if (source === "./pumpkin-assets.js" || source.endsWith("/pumpkin-assets.js") || fromSolverDir("pumpkin", "assets")) {
85
+ return `${VIRTUAL_PREFIX}pumpkin-assets`;
86
+ }
87
+ if (
88
+ source === "./highs-worker-factory.js" ||
89
+ source.endsWith("/highs-worker-factory.js") ||
90
+ fromSolverDir("highs", "worker-factory")
91
+ ) {
92
+ return `${VIRTUAL_PREFIX}highs-worker-factory`;
93
+ }
94
+ if (
95
+ source === "./pumpkin-worker-factory.js" ||
96
+ source.endsWith("/pumpkin-worker-factory.js") ||
97
+ fromSolverDir("pumpkin", "worker-factory")
98
+ ) {
99
+ return `${VIRTUAL_PREFIX}pumpkin-worker-factory`;
100
+ }
101
+ if (
102
+ source === "./highs-node-runtime.js" ||
103
+ source.endsWith("/highs-node-runtime.js") ||
104
+ fromSolverDir("highs", "node-runtime")
105
+ ) {
106
+ return `${VIRTUAL_PREFIX}highs-node-runtime`;
107
+ }
108
+ if (
109
+ source === "./pumpkin-node-runtime.js" ||
110
+ source.endsWith("/pumpkin-node-runtime.js") ||
111
+ fromSolverDir("pumpkin", "node-runtime")
112
+ ) {
113
+ return `${VIRTUAL_PREFIX}pumpkin-node-runtime`;
114
+ }
115
+ if (source === "./z3-assets.js" || source.endsWith("/z3-assets.js") || fromSolverDir("z3", "assets")) {
116
+ return `${VIRTUAL_PREFIX}z3-assets`;
117
+ }
118
+ if (source === "z3-solver") {
119
+ return `${VIRTUAL_PREFIX}z3-solver`;
120
+ }
121
+ if (source === "glpk.js" || source === "glpk.js/node") {
122
+ return `${VIRTUAL_PREFIX}glpk`;
123
+ }
124
+ if (source.startsWith("node:") || source === "module") {
125
+ return `${VIRTUAL_PREFIX}node-stub`;
126
+ }
127
+ return null;
128
+ },
129
+ load(id) {
130
+ if (!id.startsWith(VIRTUAL_PREFIX)) {
131
+ return null;
132
+ }
133
+ const key = id.slice(VIRTUAL_PREFIX.length);
134
+ switch (key) {
135
+ case "highs-assets":
136
+ return "export function getBundledWasmUrl() { return ''; }\n";
137
+ case "pumpkin-assets":
138
+ return "export function getBundledPumpkinWasmUrl() { return ''; }\n";
139
+ case "highs-worker-factory":
140
+ return "export function createHighsWorker() { throw new Error('Workers are disabled in single-file offline builds; pass { useWorker: false }.'); }\n";
141
+ case "pumpkin-worker-factory":
142
+ return "export function createPumpkinWorker() { throw new Error('Workers are disabled in single-file offline builds; pass { useWorker: false }.'); }\n";
143
+ case "highs-node-runtime":
144
+ return "export async function loadNodeHighs() { throw new Error('Node runtime is unavailable in browser builds.'); }\n";
145
+ case "pumpkin-node-runtime":
146
+ return [
147
+ "export async function readPumpkinWasmFileUrl() { throw new Error('Node runtime is unavailable in browser builds.'); }",
148
+ "export async function readBundledPumpkinWasmBytes() { throw new Error('Node runtime is unavailable in browser builds.'); }",
149
+ ].join("\n");
150
+ case "z3-assets":
151
+ return "export function getBundledZ3AssetUrls() { throw new Error('Z3 is unsupported in offline single-file HTML builds (SharedArrayBuffer requires COOP/COEP headers).'); }\n";
152
+ case "z3-solver":
153
+ return "export function init() { throw new Error('Z3 is unsupported in offline single-file HTML builds (SharedArrayBuffer requires COOP/COEP headers).'); }\nexport default { init };\n";
154
+ case "glpk":
155
+ return "export default function glpkStub() { throw new Error('GLPK is not bundled in this single-file build.'); }\n";
156
+ case "node-stub":
157
+ return [
158
+ "export default {};",
159
+ "export const existsSync = () => false;",
160
+ "export const fileURLToPath = () => '';",
161
+ "export const createRequire = () => () => { throw new Error('Node runtime is unavailable in browser builds.'); };",
162
+ "export const readFile = async () => { throw new Error('Node runtime is unavailable in browser builds.'); };",
163
+ "export const dirname = () => '';",
164
+ "export const resolve = () => '';",
165
+ "export const join = (...parts) => parts.join('/');",
166
+ ].join("\n");
167
+ default:
168
+ return null;
169
+ }
170
+ },
171
+ transformIndexHtml: {
172
+ order: "post",
173
+ handler(html) {
174
+ const wasmDir = resolveWasmDir();
175
+ const tags = solvers.map((solver) => {
176
+ const wasmPath = path.join(wasmDir, `${solver}.wasm`);
177
+ if (!existsSync(wasmPath)) {
178
+ throw new Error(`WaSHI offline plugin could not find ${wasmPath}`);
179
+ }
180
+ const b64Gz = gzipSync(readFileSync(wasmPath), { level: 9 }).toString("base64");
181
+ return {
182
+ tag: "script",
183
+ attrs: { type: "text/plain", id: `washi-wasm-${solver}-gz` },
184
+ children: b64Gz,
185
+ injectTo: "head-prepend",
186
+ };
187
+ });
188
+ return { html, tags };
189
+ },
190
+ },
191
+ };
192
+ }
193
+ ```
194
+
195
+ ## Step 2: Configure `vite.config.ts`
196
+
197
+ Pair `viteSingleFile()` with `washiSingleHtmlWasmPlugin(...)` and inline all assets (`assetsInlineLimit: 100_000_000`, `cssCodeSplit: false`, `minify: true`):
198
+
199
+ > **Vite 8 Note**: Use `minify: true` (or omit `minify` to keep Vite's default minifier). Do **not** set `minify: "esbuild"` unless `esbuild` is explicitly installed, because Vite 8 uses Oxc/Rolldown by default.
200
+
201
+ ```ts
202
+ import { defineConfig } from "vite";
203
+ import { viteSingleFile } from "vite-plugin-singlefile";
204
+ import { washiSingleHtmlWasmPlugin } from "./vite-washi-offline.mjs";
205
+
206
+ export default defineConfig({
207
+ plugins: [
208
+ washiSingleHtmlWasmPlugin({ solvers: ["highs", "pumpkin"] }),
209
+ viteSingleFile(),
210
+ ],
211
+ build: {
212
+ outDir: "dist",
213
+ assetsInlineLimit: 100_000_000,
214
+ cssCodeSplit: false,
215
+ minify: true,
216
+ },
217
+ });
218
+ ```
219
+
220
+ ## Step 3: Add Browser Gzip-WASM Hydration (`src/washi-offline.ts`)
221
+
222
+ Add `src/washi-offline.ts` to decompress the embedded `<script type="text/plain">` blocks at startup, encode them as `data:application/wasm;base64,...` data URLs via `FileReader.readAsDataURL`, and register them with WaSHI before solving:
223
+
224
+ <!-- washi-single-html:runtime-helper -->
225
+ ```ts
226
+ import { setHighsWasmUrl } from "@ohtaman/washi/solvers/highs";
227
+ import { setPumpkinWasmUrl } from "@ohtaman/washi/solvers/pumpkin";
228
+
229
+ export type OfflineSolverName = "highs" | "pumpkin";
230
+
231
+ let hydrationPromise: Promise<void> | null = null;
232
+
233
+ export async function inflateGzipBase64ToBytes(base64Gz: string): Promise<Uint8Array<ArrayBuffer>> {
234
+ const binary = atob(base64Gz.trim());
235
+ const compressed = new Uint8Array(binary.length);
236
+ for (let i = 0; i < binary.length; i++) {
237
+ compressed[i] = binary.charCodeAt(i);
238
+ }
239
+ const stream = new Blob([compressed]).stream().pipeThrough(new DecompressionStream("gzip"));
240
+ const buffer = await new Response(stream).arrayBuffer();
241
+ return new Uint8Array(buffer);
242
+ }
243
+
244
+ export function bytesToWasmDataUrl(bytes: Uint8Array<ArrayBuffer>): Promise<string> {
245
+ return new Promise((resolve, reject) => {
246
+ const reader = new FileReader();
247
+ reader.onload = () => {
248
+ if (typeof reader.result === "string") {
249
+ resolve(reader.result);
250
+ } else {
251
+ reject(new Error("Expected FileReader.readAsDataURL() to produce a string."));
252
+ }
253
+ };
254
+ reader.onerror = () => reject(reader.error ?? new Error("Failed to encode WASM bytes as data URL."));
255
+ reader.readAsDataURL(new Blob([bytes], { type: "application/wasm" }));
256
+ });
257
+ }
258
+
259
+ async function loadSolverDataUrl(solver: OfflineSolverName): Promise<string> {
260
+ const el = document.getElementById(`washi-wasm-${solver}-gz`);
261
+ const payload = el?.textContent?.trim();
262
+ if (!payload) {
263
+ throw new Error(`Missing embedded gzipped WASM element #washi-wasm-${solver}-gz.`);
264
+ }
265
+ const wasmBytes = await inflateGzipBase64ToBytes(payload);
266
+ return bytesToWasmDataUrl(wasmBytes);
267
+ }
268
+
269
+ /**
270
+ * Hydrates embedded gzipped WASM payloads once before calling Model.solve() or Model.check().
271
+ */
272
+ export function hydrateOfflineWashiSolvers(
273
+ solvers: ReadonlyArray<OfflineSolverName> = ["highs", "pumpkin"],
274
+ ): Promise<void> {
275
+ if (!hydrationPromise) {
276
+ hydrationPromise = (async () => {
277
+ const unique = Array.from(new Set(solvers));
278
+ await Promise.all(
279
+ unique.map(async (solver) => {
280
+ const dataUrl = await loadSolverDataUrl(solver);
281
+ if (solver === "highs") {
282
+ setHighsWasmUrl(dataUrl);
283
+ } else {
284
+ setPumpkinWasmUrl(dataUrl);
285
+ }
286
+ }),
287
+ );
288
+ })();
289
+ }
290
+ return hydrationPromise;
291
+ }
292
+ ```
293
+
294
+ ## Step 4: Model, Solve with `{ useWorker: false }`, and Verify
295
+
296
+ Always call `await hydrateOfflineWashiSolvers(...)` once before solving, pass `{ useWorker: false }` in every `solve()` / `check()` call, and assert `m.verify().valid` (never hardcode solver answers in UI state):
297
+
298
+ ```ts
299
+ import katex from "katex";
300
+ import "katex/dist/katex.min.css";
301
+ import { Model, expr, maximize } from "@ohtaman/washi";
302
+ import { hydrateOfflineWashiSolvers } from "./washi-offline";
303
+
304
+ async function runOptimization() {
305
+ await hydrateOfflineWashiSolvers(["highs", "pumpkin"]);
306
+
307
+ const m = new Model({ name: "production-mix" });
308
+ const x = m.continuous("x", { lb: 0, ub: 4 });
309
+ const y = m.continuous("y", { lb: 0, ub: 6 });
310
+ m.constraint(expr`${x} + ${y} <= 7`, "capacity");
311
+ m.objective(maximize(expr`3 * ${x} + 2 * ${y}`));
312
+
313
+ const status = await m.solve({ useWorker: false });
314
+ const report = m.verify();
315
+ if (!report.valid) {
316
+ throw new Error(`Solution verification failed: ${JSON.stringify(report.violations)}`);
317
+ }
318
+
319
+ document.getElementById("formula")!.innerHTML = katex.renderToString(
320
+ String.raw`\max\; 3x + 2y = ${m.objectiveValue}\quad (\text{${status}})`,
321
+ );
322
+ }
323
+
324
+ void runOptimization();
325
+ ```
326
+
327
+ ## Verification Checklist (Mandatory Before Delivering)
328
+
329
+ 1. **Build output check**: Verify `npm run build` outputs **only** `dist/index.html` (no emitted `.wasm`, `.js`, `.css`, or font files) and keeps WASM compressed (`~2.4 MiB` for HiGHS + Pumpkin Base64 gzip before JS/CSS/fonts, compared to `> 8.6 MiB` uncompressed Base64).
330
+ 2. **No external URLs in HTML**: Check `dist/index.html` for `<script src="http...`, `<link href="http...`, or CDN fallback URLs.
331
+ 3. **Headless Chrome `file://` E2E check**:
332
+ - Open `file:///absolute/path/to/dist/index.html` in Chromium/Playwright.
333
+ - Intercept `page.on("request", ...)` and assert **zero** `http://` or `https://` requests occur (`data:` only).
334
+ - Assert **zero** `console` errors and **zero** `pageerror` exceptions.
335
+ - Interact with inputs and confirm real solver output (`Optimal` / `Sat` / `Unsat` / `unsatCore`) plus third-party UI rendering updates cleanly.