@shipvo/sim 0.0.0-stage → 0.1.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 (4) hide show
  1. package/LICENSE +73 -0
  2. package/README.md +11 -2
  3. package/package.json +38 -3
  4. package/server.mjs +205 -0
package/LICENSE ADDED
@@ -0,0 +1,73 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10
+
11
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12
+
13
+ "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14
+
15
+ "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16
+
17
+ "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18
+
19
+ "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20
+
21
+ "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22
+
23
+ "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24
+
25
+ "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26
+
27
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28
+
29
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30
+
31
+ 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32
+
33
+ 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34
+
35
+ (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36
+
37
+ (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38
+
39
+ (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40
+
41
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42
+
43
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44
+
45
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46
+
47
+ 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48
+
49
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50
+
51
+ 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52
+
53
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54
+
55
+ END OF TERMS AND CONDITIONS
56
+
57
+ APPENDIX: How to apply the Apache License to your work.
58
+
59
+ To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60
+
61
+ Copyright [yyyy] [name of copyright owner]
62
+
63
+ Licensed under the Apache License, Version 2.0 (the "License");
64
+ you may not use this file except in compliance with the License.
65
+ You may obtain a copy of the License at
66
+
67
+ http://www.apache.org/licenses/LICENSE-2.0
68
+
69
+ Unless required by applicable law or agreed to in writing, software
70
+ distributed under the License is distributed on an "AS IS" BASIS,
71
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72
+ See the License for the specific language governing permissions and
73
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,12 @@
1
- # Temporary Holding Version
1
+ # @shipvo/sim
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Runs a Shipvo app in a phone-sized headless browser (Playwright, Pixel 5 viewport) and gives agents what a person with a screen reader gets: the accessibility tree with refs, tap/type/scroll/back, screenshots, system permission sheets, and a simulated device (camera, location, biometrics, payments, notifications, share, network) whose state the agent sets.
4
+
5
+ ```bash
6
+ shipvo sim # in an app created with `shipvo init`: builds the web bundle and serves it on :4545
7
+ npx shipvo-sim --dist ./sim-dist --app myshop
8
+ ```
9
+
10
+ HTTP API (used by `@shipvo/mcp`): `POST /session {session, app, seed_cart, dark, device}`, `POST /act {session, action, ...}` with actions `screen tap type scroll back screenshot set_device push_notification notifications open_notification device_log device_reset`, and a per-session mock control plane at `/s/<session>/...` that records the orders the app posts (`GET /s/<session>/orders`).
11
+
12
+ `app` can be `myshop` (the local build), `myshop@r13` (a published release) or `myshop@latest`.
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@shipvo/sim",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "license": "Apache-2.0",
6
+ "description": "The Shipvo simulator: runs a Shipvo app's web build in a phone-sized headless browser and exposes it to agents (accessibility tree, tap/type/scroll, simulated device, mock backend). Used by @shipvo/mcp and `shipvo sim`.",
7
+ "bin": {
8
+ "shipvo-sim": "server.mjs"
9
+ },
10
+ "exports": {
11
+ "./server.mjs": "./server.mjs",
12
+ "./package.json": "./package.json"
13
+ },
14
+ "files": [
15
+ "server.mjs",
16
+ "README.md"
17
+ ],
18
+ "peerDependencies": {
19
+ "playwright": ">=1.50"
20
+ },
21
+ "keywords": [
22
+ "shipvo",
23
+ "simulator",
24
+ "react-native-web",
25
+ "playwright",
26
+ "ai-agents"
27
+ ],
28
+ "homepage": "https://github.com/shipvo/shipvo#readme",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/shipvo/shipvo.git",
32
+ "directory": "packages/sim"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "provenance": true
37
+ },
38
+ "devDependencies": {
39
+ "playwright": "1.63.0"
40
+ }
6
41
  }
package/server.mjs ADDED
@@ -0,0 +1,205 @@
1
+ #!/usr/bin/env node
2
+ // Shipvo UI simulator: runs the real app UI (React Native Web build) in a phone-sized headless browser,
3
+ // and lets an agent see the screen as an accessibility tree and act on it: tap, type, scroll, back.
4
+ // No emulator, no device. Each session also gets a mock control plane that records orders for grading.
5
+ // shipvo sim (or: node packages/sim/server.mjs) [--port 4545] [--dir /tmp/pn-ui] [--dist ./sim-dist] [--app <id>]
6
+ // Reads shipvo.json in the current directory (appId, name, controlPlane) when present.
7
+ import http from "node:http";
8
+ import { readFileSync, existsSync, writeFileSync, appendFileSync, mkdirSync, statSync } from "node:fs";
9
+ import { join, extname, dirname } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ import { createRequire } from "node:module";
12
+ import { execSync } from "node:child_process";
13
+ // Playwright: the app's own install first (its browsers match it), then this package's, then a global one.
14
+ const require_ = createRequire(import.meta.url);
15
+ let pw;
16
+ for (const get of [() => createRequire(join(process.cwd(), "package.json"))("playwright"), () => require_("playwright"), () => require_(join(execSync("npm root -g").toString().trim(), "playwright"))]) {
17
+ try { pw = get(); break; } catch {}
18
+ }
19
+ if (!pw) { console.error("playwright is not installed: npm i -D playwright && npx playwright install chromium"); process.exit(2); }
20
+ const { chromium, devices } = pw;
21
+
22
+ const here = dirname(fileURLToPath(import.meta.url));
23
+ const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d; };
24
+ let CFG = {}; try { CFG = JSON.parse(readFileSync(join(process.cwd(), "shipvo.json"), "utf8")); } catch {}
25
+ const PORT = Number(arg("port", 4545)), DIR = arg("dir", "/tmp/pn-ui"), DIST = arg("dist", join(process.cwd(), "sim-dist"));
26
+ const DEFAULT_APP = arg("app", CFG.appId || "tide"), APP_NAME = CFG.name || "Tide & Tackle";
27
+ // Published releases: open_app("tide@r13") loads the web artifact that `shipvo publish` stored next to the phone bundle.
28
+ const CONTROL = (process.env.PN_CONTROL || process.env.CONTENT_FROM || CFG.controlPlane || "https://api.shipvo.dev").replace(/\/$/, "");
29
+ async function resolveApp(spec) {
30
+ const m = /^([a-z0-9-]+)(?:@(?:r?(\d+)|(latest)))?$/.exec(String(spec || DEFAULT_APP)); if (!m) throw new Error(`bad app spec "${spec}": use "${DEFAULT_APP}", "${DEFAULT_APP}@r13" or "${DEFAULT_APP}@latest"`);
31
+ const [, app, rel] = m;
32
+ const hasLocal = existsSync(join(DIST, "index.html"));
33
+ if (!rel && !m[3] && hasLocal && app === DEFAULT_APP) return { app, url: `http://localhost:${PORT}/app/`, release: "local" }; // the local build (development)
34
+ // otherwise a published release: the one asked for, or the latest (hosted: there is no local build)
35
+ let n = rel ? Number(rel) : null;
36
+ if (!n) { const r = await fetch(`${CONTROL}/w/${app}/releases.json`); if (!r.ok) throw new Error(`no published web artifact for ${app}`); n = (await r.json()).latest; }
37
+ // Served through this process so the page and its mock backend share one origin (a page on https cannot fetch http://localhost).
38
+ return { app, url: `http://localhost:${PORT}/w/${app}/r${n}/index.html`, release: n };
39
+ }
40
+ mkdirSync(DIR, { recursive: true });
41
+ const MIME = { ".html": "text/html", ".js": "text/javascript", ".json": "application/json", ".png": "image/png", ".ico": "image/x-icon", ".ttf": "font/ttf", ".css": "text/css" };
42
+ const browser = await chromium.launch();
43
+ const sessions = new Map();
44
+
45
+ const phone = { ...devices["Pixel 5"], viewport: { width: 393, height: 851 } };
46
+
47
+ async function newSession(id, opts = {}) {
48
+ if (sessions.has(id)) await sessions.get(id).ctx.close();
49
+ const target = await resolveApp(opts.app);
50
+ writeFileSync(join(DIR, `${id}.json`), JSON.stringify({ orders: [] })); writeFileSync(join(DIR, `${id}.json.log`), "");
51
+ const ctx = await browser.newContext({ ...phone, colorScheme: opts.dark ? "dark" : "light" });
52
+ await ctx.addInitScript((cfg) => { globalThis.__PN_SIM__ = cfg; }, { baseUrl: `http://localhost:${PORT}/s/${id}`, appId: target.app, appName: APP_NAME, seed_cart: opts.seed_cart ?? null, device: opts.device ?? null });
53
+ const page = await ctx.newPage();
54
+ await page.goto(target.url, { waitUntil: "networkidle" });
55
+ await page.waitForTimeout(300);
56
+ sessions.set(id, { ctx, page, app: target.app, release: target.release, startedAt: new Date().toISOString() });
57
+ }
58
+
59
+ async function screen(page) {
60
+ await page.waitForTimeout(150);
61
+ // Phones only expose the items of a horizontal list that are on screen; hide the rest, as a phone would,
62
+ // so an agent learns to swipe the rail ("scroll right <ref>") exactly as it must on a device.
63
+ await page.evaluate(() => {
64
+ for (const el of document.querySelectorAll("[data-pn-offscreen]")) { el.removeAttribute("aria-hidden"); el.removeAttribute("data-pn-offscreen"); }
65
+ // A modal sheet (accessibilityViewIsModal / aria-modal) hides everything behind it from assistive tech on phones.
66
+ const modal = [...document.querySelectorAll('[aria-modal="true"]')].pop();
67
+ if (modal) for (let node = modal; node && node !== document.body; node = node.parentElement)
68
+ for (const sib of node.parentElement?.children ?? []) if (sib !== node && !sib.hasAttribute("aria-hidden")) { sib.setAttribute("aria-hidden", "true"); sib.setAttribute("data-pn-offscreen", "1"); }
69
+ for (const sc of document.querySelectorAll("div")) {
70
+ const cs = getComputedStyle(sc);
71
+ if (!/(auto|scroll)/.test(cs.overflowX) || sc.scrollWidth <= sc.clientWidth + 1) continue;
72
+ const box = sc.getBoundingClientRect();
73
+ const row = sc.firstElementChild; if (!row) continue;
74
+ for (const item of row.children) {
75
+ const r = item.getBoundingClientRect();
76
+ if (r.right <= box.left + 1 || r.left >= box.right - 1) { item.setAttribute("aria-hidden", "true"); item.setAttribute("data-pn-offscreen", "1"); }
77
+ }
78
+ }
79
+ });
80
+ // What is hidden from assistive tech must not appear at all: this Playwright keeps aria-hidden nodes but strips
81
+ // their names. `inert` removes them from the accessibility tree; it is set only for the snapshot and removed after.
82
+ await page.evaluate(() => { for (const el of document.querySelectorAll('[aria-hidden="true"]')) { el.setAttribute("data-pn-prev-display", el.style.display || ""); el.style.setProperty("display", "none", "important"); } });
83
+ const tree = await page.locator("body").ariaSnapshot({ mode: "ai" });
84
+ await page.evaluate(() => { for (const el of document.querySelectorAll("[data-pn-prev-display]")) { const prev = el.getAttribute("data-pn-prev-display"); if (prev) el.style.display = prev; else el.style.removeProperty("display"); el.removeAttribute("data-pn-prev-display"); } });
85
+ const lines = tree.split("\n").filter((l) => !/^\s*- generic \[ref=e\d+\]:?\s*$/.test(l));
86
+ // A screen reader announces a control's label, not the words inside it (Android and iOS group a pressable's
87
+ // children into one element). Drop the inner text lines of labelled controls, as the phones do.
88
+ const out = []; let hideBelow = -1;
89
+ for (const l of lines) {
90
+ const indent = l.search(/\S/);
91
+ if (hideBelow >= 0 && indent > hideBelow) continue;
92
+ hideBelow = -1;
93
+ if (/\[aria-hidden\]/.test(l)) { hideBelow = indent; continue; } // hidden from assistive tech: not on screen
94
+ out.push(l);
95
+ if (/^\s*- (button|radio|link|checkbox|switch|tab) "[^"]+"/.test(l) && /:\s*$/.test(l)) hideBelow = indent;
96
+ }
97
+ return out.join("\n");
98
+ }
99
+
100
+ function log(id, action, ok, extra = {}) { appendFileSync(join(DIR, `${id}.json.log`), JSON.stringify({ at: Date.now(), name: action, ok, ...extra }) + "\n"); }
101
+
102
+ async function act(id, body) {
103
+ const s = sessions.get(id); if (!s) throw new Error(`no session '${id}': call /session first`);
104
+ const { page } = s; const loc = (ref) => page.locator(`aria-ref=${ref}`);
105
+ switch (body.action) {
106
+ case "screen": break;
107
+ case "tap": await loc(body.ref).click({ timeout: 3000 }); break;
108
+ case "type": {
109
+ // A labelled text field may resolve to its wrapper; type into the real input inside it, as a phone focuses the field.
110
+ let t = loc(body.ref);
111
+ const kind = await t.evaluate((el) => (/^(INPUT|TEXTAREA)$/.test(el.tagName) || el.isContentEditable) ? "field" : el.querySelector("input, textarea") ? "wrapper" : (el.getAttribute("aria-label") || el.textContent || "").trim(), { timeout: 3000 });
112
+ if (kind === "wrapper") t = t.locator("input, textarea").first();
113
+ else if (kind !== "field") {
114
+ // Typing "on" a label or heading: a person would go to the field of that name. One match, or a clear error.
115
+ const named = page.getByRole("textbox", { name: kind, exact: true });
116
+ if ((await named.count()) !== 1) throw new Error(`${body.ref} is not a text field. Type into a "textbox" ref.`);
117
+ t = named;
118
+ }
119
+ await t.fill(String(body.text ?? ""), { timeout: 3000 }); if (body.enter) await t.press("Enter"); break;
120
+ }
121
+ case "scroll": {
122
+ const target = body.ref ? loc(body.ref) : page.locator("body");
123
+ const box = await target.boundingBox().catch(() => null);
124
+ if (box) await page.mouse.move(box.x + box.width / 2, box.y + Math.min(box.height / 2, 400));
125
+ await page.mouse.wheel(body.direction === "right" ? 300 : body.direction === "left" ? -300 : 0, body.direction === "up" ? -600 : body.direction === "down" ? 600 : 0);
126
+ break;
127
+ }
128
+ // Simulated device: what the phone "has" and what happens to it. See @shipvo/device.
129
+ case "set_device": await page.evaluate((d) => globalThis.__pnDevice?.set(d), body.device ?? {}); break;
130
+ case "push_notification": await page.evaluate((n) => globalThis.__pnDevice?.push(n), { title: body.title ?? "", body: body.body ?? "", data: body.data ?? {} }); break;
131
+ case "notifications": return { notifications: await page.evaluate(() => globalThis.__pnDevice?.notifications() ?? []), screen: await screen(page) };
132
+ case "open_notification": { const ok = await page.evaluate((nid) => globalThis.__pnDevice?.openNotification(nid), body.id); if (!ok) throw new Error("no such notification"); await page.waitForTimeout(400); break; }
133
+ case "device_log": return { log: await page.evaluate(() => globalThis.__pnDevice?.log() ?? []), capabilities: await page.evaluate(() => globalThis.__pnDevice?.capabilities() ?? null), screen: await screen(page) };
134
+ case "diag": {
135
+ const r = await page.evaluate(async () => {
136
+ const cfg = globalThis.__PN_SIM__ ?? {}; const out = { baseUrl: cfg.baseUrl, origin: location.origin };
137
+ try { const res = await fetch(`${cfg.baseUrl}/o/${cfg.appId ?? "tide"}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ order: { id: "DIAG", lines: [], total: 0 } }) }); out.post = res.status; } catch (e) { out.postError = String(e); }
138
+ try { const res = await fetch(`${cfg.baseUrl}/c/${cfg.appId}/content.json`); out.content = res.status; } catch (e) { out.contentError = String(e); }
139
+ return out;
140
+ });
141
+ return { diag: r, screen: await screen(page) };
142
+ }
143
+ case "device_reset": await page.evaluate((d) => globalThis.__pnDevice?.reset(d), body.device ?? {}); break;
144
+ case "back": { const b = page.getByRole("button", { name: "Back", exact: true }); if (await b.count()) await b.first().click(); else throw new Error("no Back button on this screen"); break; }
145
+ case "screenshot": { const p = join(DIR, `${id}-${Date.now()}.png`); await page.screenshot({ path: p }); return { path: p, screen: await screen(page) }; }
146
+ default: throw new Error(`unknown action '${body.action}'. Actions: screen, tap, type, scroll, back, screenshot, set_device, push_notification, notifications, open_notification, device_log, device_reset`);
147
+ }
148
+ return { screen: await screen(page) };
149
+ }
150
+
151
+ const WCACHE = new Map();
152
+ const server = http.createServer(async (req, res) => {
153
+ const url = new URL(req.url, "http://x");
154
+ // CORS plus Chromium's private-network preflight: the app page comes from the public control plane (https) and
155
+ // posts orders and telemetry to this loopback backend.
156
+ const CORS = { "access-control-allow-origin": "*", "access-control-allow-headers": "*", "access-control-allow-methods": "GET,POST,OPTIONS", "access-control-allow-private-network": "true" };
157
+ const send = (code, obj, type = "application/json") => { res.writeHead(code, { "content-type": type, ...CORS }); res.end(type === "application/json" ? JSON.stringify(obj) : obj); };
158
+ try {
159
+ if (req.method === "OPTIONS") return send(204, "", "text/plain");
160
+ // the app's static web build
161
+ if (url.pathname.startsWith("/_expo/") || url.pathname.startsWith("/assets/") || url.pathname === "/favicon.ico") {
162
+ const p = join(DIST, decodeURIComponent(url.pathname)); if (existsSync(p)) return send(200, readFileSync(p), MIME[extname(p)] ?? "application/octet-stream");
163
+ }
164
+ // released web artifacts, proxied from the control plane and cached (immutable per release)
165
+ if (url.pathname.startsWith("/w/")) {
166
+ const key = url.pathname; let hit = WCACHE.get(key);
167
+ if (!hit) { const r = await fetch(`${CONTROL}${key}`); if (!r.ok) return send(r.status, { error: "artifact" }); hit = { type: r.headers.get("content-type") ?? "application/octet-stream", body: Buffer.from(await r.arrayBuffer()) }; WCACHE.set(key, hit); }
168
+ return send(200, hit.body, hit.type);
169
+ }
170
+ if (url.pathname.startsWith("/app/")) {
171
+ let p = join(DIST, url.pathname.slice(5) || "index.html"); if (!existsSync(p) || statSync(p).isDirectory()) p = join(DIST, "index.html");
172
+ return send(200, readFileSync(p), MIME[extname(p)] ?? "application/octet-stream");
173
+ }
174
+ // mock control plane per session
175
+ const m = url.pathname.match(/^\/s\/([\w-]+)\/(.*)$/);
176
+ if (m) {
177
+ const [, id, rest] = m;
178
+ if (rest.startsWith("c/")) {
179
+ // Use the same live content as devices when CONTENT_FROM points at a control plane; else the bundled default.
180
+ if (process.env.CONTENT_FROM) { try { const r = await fetch(`${process.env.CONTENT_FROM}/${rest}`); if (r.ok) { res.writeHead(200, { "content-type": "application/json", ...CORS }); return res.end(await r.text()); } } catch {} }
181
+ return send(404, { error: "no_content" });
182
+ }
183
+ if (rest === "orders" && req.method === "GET") { try { return send(200, JSON.parse(readFileSync(join(DIR, `${id}.json`), "utf8"))); } catch { return send(404, { error: "no_session" }); } }
184
+ if (rest.startsWith("o/") && req.method === "POST") {
185
+ let b = ""; for await (const ch of req) b += ch;
186
+ const f = join(DIR, `${id}.json`); const st = JSON.parse(readFileSync(f, "utf8")); st.orders.push(JSON.parse(b).order); writeFileSync(f, JSON.stringify(st));
187
+ return send(202, { ok: true });
188
+ }
189
+ return send(202, { ok: true }); // telemetry etc.
190
+ }
191
+ // agent API
192
+ if (req.method !== "POST") return send(404, { error: "not found" });
193
+ let raw = ""; for await (const ch of req) raw += ch; const body = raw ? JSON.parse(raw) : {};
194
+ if (url.pathname === "/sessions") return send(200, { ok: true, sessions: [...sessions.entries()].map(([id, s]) => ({ session: id, app: s.app, release: s.release, started_at: s.startedAt ?? null, url: s.page.url() })) });
195
+ if (url.pathname === "/session") { await newSession(body.session, body); const s = sessions.get(body.session); log(body.session, "start", true, { app: s.app, release: s.release }); return send(200, { ok: true, app: s.app, release: s.release, screen: await screen(s.page) }); }
196
+ if (url.pathname === "/act") {
197
+ try { const r = await act(body.session, body); log(body.session, body.action, true, body.ref ? { ref: body.ref } : {}); return send(200, { ok: true, ...r }); }
198
+ catch (e) { log(body.session, body.action, false); const s = sessions.get(body.session); return send(200, { ok: false, error: String(e.message).split("\n")[0], screen: s ? await screen(s.page) : null }); }
199
+ }
200
+ send(404, { error: "not found" });
201
+ } catch (e) { send(500, { error: String(e) }); }
202
+ });
203
+ // Agents and parity runs pause between actions; keep idle connections open well beyond Node's 5 s default.
204
+ server.keepAliveTimeout = 300_000; server.headersTimeout = 310_000; server.requestTimeout = 0;
205
+ server.listen(PORT, () => console.log(`Shipvo UI simulator on http://localhost:${PORT} (sessions in ${DIR})`));