@parcha/pi-browser 0.0.0-stage → 0.1.0-beta.14

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 (108) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +33 -0
  4. package/README.md +348 -2
  5. package/dist/coding-agent-local.d.ts +16 -0
  6. package/dist/coding-agent-local.js +138 -0
  7. package/dist/coding-agent.d.ts +79 -0
  8. package/dist/coding-agent.js +448 -0
  9. package/dist/core/contract.d.ts +26 -0
  10. package/dist/core/contract.js +154 -0
  11. package/dist/core/custody.d.ts +117 -0
  12. package/dist/core/custody.js +126 -0
  13. package/dist/core/decisions.d.ts +43 -0
  14. package/dist/core/decisions.js +4 -0
  15. package/dist/core/downloads.d.ts +35 -0
  16. package/dist/core/downloads.js +131 -0
  17. package/dist/core/effects.d.ts +63 -0
  18. package/dist/core/effects.js +256 -0
  19. package/dist/core/evidence.d.ts +43 -0
  20. package/dist/core/evidence.js +6 -0
  21. package/dist/core/failures.d.ts +36 -0
  22. package/dist/core/failures.js +68 -0
  23. package/dist/core/find.d.ts +32 -0
  24. package/dist/core/find.js +179 -0
  25. package/dist/core/guard.d.ts +6 -0
  26. package/dist/core/guard.js +25 -0
  27. package/dist/core/host.d.ts +328 -0
  28. package/dist/core/host.js +2 -0
  29. package/dist/core/images.d.ts +37 -0
  30. package/dist/core/images.js +60 -0
  31. package/dist/core/lease.d.ts +16 -0
  32. package/dist/core/lease.js +30 -0
  33. package/dist/core/receipts.d.ts +19 -0
  34. package/dist/core/receipts.js +22 -0
  35. package/dist/core/redact.d.ts +13 -0
  36. package/dist/core/redact.js +83 -0
  37. package/dist/core/session-control.d.ts +25 -0
  38. package/dist/core/session-control.js +75 -0
  39. package/dist/core/sites.d.ts +33 -0
  40. package/dist/core/sites.js +102 -0
  41. package/dist/core/tools.d.ts +72 -0
  42. package/dist/core/tools.js +200 -0
  43. package/dist/core/uri.d.ts +11 -0
  44. package/dist/core/uri.js +37 -0
  45. package/dist/core/usage.d.ts +19 -0
  46. package/dist/core/usage.js +44 -0
  47. package/dist/core/web.d.ts +98 -0
  48. package/dist/core/web.js +327 -0
  49. package/dist/driver/extension-worker.d.ts +6 -0
  50. package/dist/driver/extension-worker.js +121 -0
  51. package/dist/driver/stagehand.d.ts +25 -0
  52. package/dist/driver/stagehand.js +91 -0
  53. package/dist/durable-result.d.ts +6 -0
  54. package/dist/durable-result.js +2 -0
  55. package/dist/durable.d.ts +79 -0
  56. package/dist/durable.js +582 -0
  57. package/dist/index.d.ts +19 -0
  58. package/dist/index.js +20 -0
  59. package/dist/providers/browserbase-net.d.ts +13 -0
  60. package/dist/providers/browserbase-net.js +96 -0
  61. package/dist/providers/browserbase.d.ts +152 -0
  62. package/dist/providers/browserbase.js +262 -0
  63. package/dist/providers/cdp-call.d.ts +6 -0
  64. package/dist/providers/cdp-call.js +25 -0
  65. package/dist/providers/cdp.d.ts +55 -0
  66. package/dist/providers/cdp.js +423 -0
  67. package/dist/providers/http.d.ts +2 -0
  68. package/dist/providers/http.js +21 -0
  69. package/dist/providers/kernel.d.ts +49 -0
  70. package/dist/providers/kernel.js +246 -0
  71. package/dist/providers/shared.d.ts +47 -0
  72. package/dist/providers/shared.js +82 -0
  73. package/dist/recorder/credential.d.ts +9 -0
  74. package/dist/recorder/credential.js +49 -0
  75. package/dist/recorder/follow.d.ts +26 -0
  76. package/dist/recorder/follow.js +138 -0
  77. package/dist/recorder/frames.d.ts +80 -0
  78. package/dist/recorder/frames.js +309 -0
  79. package/dist/recorder/index.d.ts +4 -0
  80. package/dist/recorder/index.js +7 -0
  81. package/dist/recorder/jpeg.d.ts +8 -0
  82. package/dist/recorder/jpeg.js +70 -0
  83. package/dist/recorder/track.d.ts +107 -0
  84. package/dist/recorder/track.js +259 -0
  85. package/dist/store.d.ts +56 -0
  86. package/dist/store.js +196 -0
  87. package/dist/testing/backend.d.ts +231 -0
  88. package/dist/testing/backend.js +414 -0
  89. package/dist/testing/driver.d.ts +28 -0
  90. package/dist/testing/driver.js +32 -0
  91. package/dist/testing/index.d.ts +4 -0
  92. package/dist/testing/index.js +4 -0
  93. package/dist/testing/pages.d.ts +3 -0
  94. package/dist/testing/pages.js +10 -0
  95. package/dist/testing/sentinels.d.ts +29 -0
  96. package/dist/testing/sentinels.js +38 -0
  97. package/dist/vendor/stagehand-facade/contract.d.ts +348 -0
  98. package/dist/vendor/stagehand-facade/contract.js +155 -0
  99. package/dist/vendor/stagehand-facade/runtime.d.ts +90 -0
  100. package/dist/vendor/stagehand-facade/runtime.js +1640 -0
  101. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +15 -0
  102. package/dist/vendor/stagehand-facade/screenshot-transport.js +51 -0
  103. package/dist/vendor/stagehand-facade/tools.d.ts +31 -0
  104. package/dist/vendor/stagehand-facade/tools.js +139 -0
  105. package/dist/web.d.ts +41 -0
  106. package/dist/web.js +38 -0
  107. package/package.json +123 -4
  108. package/src/vendor/stagehand-facade/UPSTREAM.json +24 -0
@@ -0,0 +1,231 @@
1
+ import { EventEmitter } from "node:events";
2
+ import type { AttachTarget, BrowserProvider, ProviderCaps, RemoteFile, SearchResult } from "../core/host.js";
3
+ import { type Sentinels } from "./sentinels.js";
4
+ export type FakeFetchByFormat = {
5
+ markdown?: {
6
+ contentType: string;
7
+ content: string;
8
+ } | {
9
+ status: number;
10
+ };
11
+ raw?: {
12
+ contentType: string;
13
+ content: string;
14
+ } | {
15
+ status: number;
16
+ };
17
+ };
18
+ /** A vendor SDK's failure: the HTTP status is on the error, never inside the text. */
19
+ export declare class FakeProviderError extends Error {
20
+ readonly status: number;
21
+ constructor(message: string, status?: number);
22
+ }
23
+ export type LedgerRow = {
24
+ n: number;
25
+ op: string;
26
+ [field: string]: unknown;
27
+ };
28
+ export type FixturePage = {
29
+ url: string;
30
+ title: string;
31
+ text: string;
32
+ html: string;
33
+ };
34
+ export declare const fixturePage: (url: string, text: string, title?: string) => FixturePage;
35
+ export type BrokerConnection = {
36
+ name: string;
37
+ startUrl: string | null;
38
+ fields: Array<{
39
+ name: string;
40
+ type: "text" | "email" | "password" | "totp";
41
+ }>;
42
+ allowedOrigins: string[];
43
+ enrollment: boolean;
44
+ };
45
+ export type FillRequest = {
46
+ pageUrl: string;
47
+ fields: Array<{
48
+ field: string;
49
+ selector: string;
50
+ }>;
51
+ };
52
+ export type FillResult = {
53
+ status: "completed" | "failed" | "unknown";
54
+ fields: Array<{
55
+ index: number;
56
+ status: string;
57
+ errorCode?: string;
58
+ }>;
59
+ };
60
+ export type FakeBackendOptions = {
61
+ sentinels?: Sentinels;
62
+ name?: string;
63
+ caps?: Partial<ProviderCaps>;
64
+ start?: string;
65
+ pages?: Record<string, FixturePage>;
66
+ /** A URL not listed is a 404; an object answers markdown and raw apart. */
67
+ fetches?: Record<string, string | FakeFetchByFormat>;
68
+ search?: SearchResult["results"];
69
+ /** Every ledger row is also appended here as JSONL, so a killed process leaves its calls behind. */
70
+ logFile?: string;
71
+ connections?: BrokerConnection[];
72
+ downloads?: Record<string, string>;
73
+ viewport?: {
74
+ width: number;
75
+ height: number;
76
+ };
77
+ fullPageHeight?: number;
78
+ /** Device pixels per CSS pixel; a screenshot is this many times larger unless it asks for `scale: "css"`. */
79
+ deviceScale?: number;
80
+ };
81
+ export type FakeScreenshotOptions = {
82
+ fullPage?: boolean;
83
+ type?: "png" | "jpeg";
84
+ quality?: number;
85
+ scale?: "css" | "device";
86
+ };
87
+ /** A PNG or JPEG whose header declares `width` x `height`: enough for a reader that decodes the header, not a picture. */
88
+ export declare function fakeImage(type: "png" | "jpeg", width: number, height: number): Buffer;
89
+ type Session = {
90
+ id: string;
91
+ tag: string;
92
+ metadata: Record<string, string>;
93
+ state: "running" | "stopped";
94
+ url: string;
95
+ broker: boolean;
96
+ plane: string;
97
+ };
98
+ export declare class FakeBackend {
99
+ readonly sentinels: Sentinels;
100
+ readonly pages: Record<string, FixturePage>;
101
+ readonly ledger: LedgerRow[];
102
+ /** Every call the driver made on a page, in order; a read answered from a receipt never shows up here. */
103
+ readonly dispatched: Array<{
104
+ op: string;
105
+ session: string;
106
+ url: string | null;
107
+ [field: string]: unknown;
108
+ }>;
109
+ /** Emits `held` with the op name when a held call has been applied and will never be answered. */
110
+ readonly events: EventEmitter<[never]>;
111
+ readonly sessions: Map<string, Session>;
112
+ readonly provider: BrowserProvider;
113
+ readonly broker: FakeBroker;
114
+ readonly driverFace: FakeDriverFace;
115
+ private seq;
116
+ private holdOp;
117
+ private loseOp;
118
+ private failures;
119
+ private delays;
120
+ private peak;
121
+ private echoOn;
122
+ readonly opts: Required<Pick<FakeBackendOptions, "start" | "fetches" | "search" | "connections" | "downloads">> & FakeBackendOptions;
123
+ constructor(options?: FakeBackendOptions);
124
+ /** The next call of `op` is applied and recorded, then never answered. */
125
+ hold(op: string): void;
126
+ /** The next call of `op` is applied and recorded, then fails: the provider did the work and the answer was lost. */
127
+ lose(op: string): void;
128
+ /** The next `times` calls of `op` fail before they take effect. */
129
+ fail(op: string, times?: number): void;
130
+ /** `op` sleeps `ms` before it takes effect; a caller that hangs up meanwhile is not served. */
131
+ delay(op: string, ms: number): void;
132
+ /** Failure text repeats the request and every secret the backend holds. */
133
+ echo(on?: boolean): void;
134
+ endAll(): void;
135
+ goto(url: string): void;
136
+ reset(): void;
137
+ live(): Array<{
138
+ id: string;
139
+ tag: string;
140
+ }>;
141
+ liveCount(): number;
142
+ tally(): {
143
+ creates: number;
144
+ findByTag: number;
145
+ status: number;
146
+ attaches: number;
147
+ releases: number;
148
+ releaseNoops: number;
149
+ fetches: number;
150
+ searches: number;
151
+ dispatches: number;
152
+ reads: number;
153
+ peakLive: number;
154
+ liveAtEnd: number;
155
+ };
156
+ /** A failing vendor's error text: the request's credentials and the connect URLs the backend holds. */
157
+ echoText(op: string): string;
158
+ record(op: string, fields?: Record<string, unknown>): LedgerRow;
159
+ before(op: string, signal?: AbortSignal): Promise<void>;
160
+ after(op: string): Promise<void>;
161
+ noteLive(): void;
162
+ newId(prefix: string): string;
163
+ running(id: string): Session | null;
164
+ targetOf(session: Session): AttachTarget;
165
+ private makeProvider;
166
+ /** For a child's `remoteProvider` and `remoteDriver`; a held call stays open until the child dies. */
167
+ serve(): Promise<{
168
+ url: string;
169
+ close(): Promise<void>;
170
+ }>;
171
+ }
172
+ /** A held call never returns; an aborted one stops its request. */
173
+ export declare function remoteProvider(url: string, options?: {
174
+ name?: string;
175
+ caps?: Partial<ProviderCaps>;
176
+ }): BrowserProvider;
177
+ /** Counts a fill before the provider is touched and never repeats an unknown one; its failures carry only codes. */
178
+ export declare class FakeBroker {
179
+ private readonly b;
180
+ constructor(b: FakeBackend);
181
+ connections(): Promise<BrokerConnection[]>;
182
+ acquire(name: string): Promise<{
183
+ session: string;
184
+ attach: AttachTarget;
185
+ leaseExpiresAt: string;
186
+ recording: boolean | null;
187
+ }>;
188
+ heartbeat(session: string): Promise<{
189
+ leaseExpiresAt: string;
190
+ }>;
191
+ release(session: string): Promise<void>;
192
+ fill(session: string, request: FillRequest): Promise<FillResult>;
193
+ captureTotpSeed(session: string, request: {
194
+ pageUrl: string;
195
+ selector: string;
196
+ }): Promise<{
197
+ stored: boolean;
198
+ field: string;
199
+ }>;
200
+ downloads(): Promise<RemoteFile[]>;
201
+ }
202
+ export declare class FakeDriverFace {
203
+ private readonly b;
204
+ constructor(b: FakeBackend);
205
+ private session;
206
+ private pageOf;
207
+ private call;
208
+ connect(target: AttachTarget): Promise<string>;
209
+ snapshot(id: string): Promise<string>;
210
+ /** A `goto` action moves the page; any other code returns what it was given. */
211
+ run(id: string, input: {
212
+ code?: string;
213
+ actions?: Array<{
214
+ op: string;
215
+ url?: string;
216
+ [field: string]: unknown;
217
+ }>;
218
+ }): Promise<unknown>;
219
+ /** No `dispatched` row: a read of the URL is not a read of the page. */
220
+ url(id: string): Promise<string>;
221
+ /** Header-only image of the viewport (or full page) times the device scale; each capture is a dispatched row. */
222
+ screenshot(id: string, options?: FakeScreenshotOptions): Promise<{
223
+ data: string;
224
+ mimeType: string;
225
+ width: number;
226
+ height: number;
227
+ }>;
228
+ page(id: string): Promise<FixturePage>;
229
+ close(id: string): Promise<void>;
230
+ }
231
+ export {};
@@ -0,0 +1,414 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { crc32 } from "node:zlib";
3
+ import fs from "node:fs";
4
+ import http from "node:http";
5
+ import { makeSentinels } from "./sentinels.js";
6
+ /** A vendor SDK's failure: the HTTP status is on the error, never inside the text. */
7
+ export class FakeProviderError extends Error {
8
+ status;
9
+ constructor(message, status = 502) {
10
+ super(message);
11
+ this.name = "FakeProviderError";
12
+ this.status = status;
13
+ }
14
+ }
15
+ export const fixturePage = (url, text, title = "Fixture") => ({ url, title, text, html: `<main><p>${text}</p></main>` });
16
+ /** A PNG or JPEG whose header declares `width` x `height`: enough for a reader that decodes the header, not a picture. */
17
+ export function fakeImage(type, width, height) {
18
+ if (type === "jpeg") {
19
+ const sof = Buffer.from([0xff, 0xc0, 0x00, 0x0b, 0x08, height >> 8, height & 0xff, width >> 8, width & 0xff, 0x01, 0x01, 0x11, 0x00]);
20
+ return Buffer.concat([Buffer.from([0xff, 0xd8]), sof, Buffer.from([0xff, 0xd9])]);
21
+ }
22
+ const chunk = (kind, data) => {
23
+ const head = Buffer.concat([Buffer.from(kind, "ascii"), data]);
24
+ const length = Buffer.alloc(4);
25
+ length.writeUInt32BE(data.length);
26
+ const crc = Buffer.alloc(4);
27
+ crc.writeUInt32BE(crc32(head));
28
+ return Buffer.concat([length, head, crc]);
29
+ };
30
+ const ihdr = Buffer.alloc(13);
31
+ ihdr.writeUInt32BE(width, 0);
32
+ ihdr.writeUInt32BE(height, 4);
33
+ ihdr[8] = 8;
34
+ ihdr[9] = 2;
35
+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IEND", Buffer.alloc(0))]);
36
+ }
37
+ const DEFAULT_CAPS = { timeoutModel: "inactivity", maxLifetimeS: 3600, survivesDisconnect: false, releaseIsAsync: false, extension: "loaded-locally" };
38
+ export class FakeBackend {
39
+ sentinels;
40
+ pages;
41
+ ledger = [];
42
+ /** Every call the driver made on a page, in order; a read answered from a receipt never shows up here. */
43
+ dispatched = [];
44
+ /** Emits `held` with the op name when a held call has been applied and will never be answered. */
45
+ events = new EventEmitter();
46
+ sessions = new Map();
47
+ provider;
48
+ broker;
49
+ driverFace;
50
+ seq = 0;
51
+ holdOp = null;
52
+ loseOp = null;
53
+ failures = new Map();
54
+ delays = new Map();
55
+ peak = 0;
56
+ echoOn = false;
57
+ opts;
58
+ constructor(options = {}) {
59
+ this.sentinels = options.sentinels ?? makeSentinels();
60
+ this.pages = options.pages ?? {};
61
+ this.opts = {
62
+ ...options,
63
+ start: options.start ?? "about:blank",
64
+ fetches: options.fetches ?? {},
65
+ search: options.search ?? [],
66
+ downloads: options.downloads ?? {},
67
+ connections: options.connections ?? [{ name: "demo", startUrl: "https://login.sentinel.test/", fields: [{ name: "username", type: "text" }, { name: "password", type: "password" }, { name: "otp", type: "totp" }], allowedOrigins: ["https://login.sentinel.test"], enrollment: true }],
68
+ };
69
+ this.provider = this.makeProvider(options.name ?? "fake", { ...DEFAULT_CAPS, ...options.caps });
70
+ this.broker = new FakeBroker(this);
71
+ this.driverFace = new FakeDriverFace(this);
72
+ }
73
+ /** The next call of `op` is applied and recorded, then never answered. */
74
+ hold(op) { this.holdOp = op; }
75
+ /** The next call of `op` is applied and recorded, then fails: the provider did the work and the answer was lost. */
76
+ lose(op) { this.loseOp = op; }
77
+ /** The next `times` calls of `op` fail before they take effect. */
78
+ fail(op, times = 1) { this.failures.set(op, times); }
79
+ /** `op` sleeps `ms` before it takes effect; a caller that hangs up meanwhile is not served. */
80
+ delay(op, ms) { this.delays.set(op, ms); }
81
+ /** Failure text repeats the request and every secret the backend holds. */
82
+ echo(on = true) { this.echoOn = on; }
83
+ endAll() { for (const s of this.sessions.values())
84
+ s.state = "stopped"; }
85
+ goto(url) { for (const s of this.sessions.values())
86
+ if (s.state === "running")
87
+ s.url = url; }
88
+ reset() {
89
+ this.sessions.clear();
90
+ this.ledger.length = 0;
91
+ this.dispatched.length = 0;
92
+ this.seq = 0;
93
+ this.holdOp = null;
94
+ this.loseOp = null;
95
+ this.failures.clear();
96
+ this.delays.clear();
97
+ this.peak = 0;
98
+ this.echoOn = false;
99
+ }
100
+ live() { return [...this.sessions.values()].filter((s) => s.state === "running").map(({ id, tag }) => ({ id, tag })); }
101
+ liveCount() { return this.live().length; }
102
+ tally() {
103
+ const count = (op) => this.ledger.filter((r) => r.op === op).length;
104
+ return {
105
+ creates: count("create"), findByTag: count("findByTag"), status: count("status"), attaches: count("attach"), releases: count("release"), releaseNoops: count("release-noop"),
106
+ fetches: count("fetch"), searches: count("search"), dispatches: this.dispatched.filter((d) => d.op === "run").length, reads: this.dispatched.filter((d) => d.op === "read").length,
107
+ peakLive: this.peak, liveAtEnd: this.liveCount(),
108
+ };
109
+ }
110
+ /** A failing vendor's error text: the request's credentials and the connect URLs the backend holds. */
111
+ echoText(op) {
112
+ const s = this.sentinels;
113
+ const vendor = `${op} failed: authorization=Bearer ${s.runToken} x-bb-api-key=${s.bbApiKey} connect=${s.bbConnectUrl} cdp=${s.kernelCdpUrl}`;
114
+ return op.startsWith("broker.") ? `${vendor} user=${s.loginUsername} password=${s.loginPassword} totp=${s.totpSeed} vault=${s.vaultRef}` : vendor;
115
+ }
116
+ record(op, fields = {}) {
117
+ const row = { n: this.ledger.length + 1, op, ...fields };
118
+ this.ledger.push(row);
119
+ if (this.opts.logFile)
120
+ fs.appendFileSync(this.opts.logFile, `${JSON.stringify(row)}\n`);
121
+ return row;
122
+ }
123
+ async before(op, signal) {
124
+ signal?.throwIfAborted();
125
+ const ms = this.delays.get(op);
126
+ if (ms) {
127
+ await new Promise((resolve, reject) => {
128
+ const timer = setTimeout(resolve, ms);
129
+ signal?.addEventListener("abort", () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
130
+ });
131
+ }
132
+ const left = this.failures.get(op) ?? 0;
133
+ if (left > 0) {
134
+ this.failures.set(op, left - 1);
135
+ this.record(`${op}-failed`);
136
+ throw new FakeProviderError(this.echoOn ? this.echoText(op) : `${op} failed: provider unavailable`);
137
+ }
138
+ }
139
+ async after(op) {
140
+ if (this.loseOp === op) {
141
+ this.loseOp = null;
142
+ throw new FakeProviderError(`${op} was applied and its answer was lost`);
143
+ }
144
+ if (this.holdOp !== op)
145
+ return;
146
+ this.holdOp = null;
147
+ this.events.emit("held", op);
148
+ await new Promise(() => { });
149
+ }
150
+ noteLive() { this.peak = Math.max(this.peak, this.liveCount()); }
151
+ newId(prefix) { this.seq += 1; return `${prefix}-${this.seq}`; }
152
+ running(id) { const s = this.sessions.get(id); return s && s.state === "running" ? s : null; }
153
+ targetOf(session) {
154
+ const url = this.sentinels.bbConnectUrl.replace(/sessionId=[^&]+/, `sessionId=${session.id}`);
155
+ if (!session.broker)
156
+ return { sdkCdpUrl: url };
157
+ return { sdkCdpUrl: `ws://127.0.0.1:1/vm-local/?sessionId=${session.id}`, dial: { url: this.sentinels.kernelCdpUrl, headers: { Authorization: `Bearer ${this.sentinels.brokerCapability}` } } };
158
+ }
159
+ makeProvider(name, caps) {
160
+ const b = this;
161
+ return {
162
+ name,
163
+ caps,
164
+ async create(spec, signal) {
165
+ await b.before("create", signal);
166
+ const id = b.newId("fake_sess");
167
+ b.sessions.set(id, { id, tag: spec.tag, metadata: { ...spec.metadata }, state: "running", url: b.opts.start, broker: false, plane: "default" });
168
+ b.noteLive();
169
+ b.record("create", { id, tag: spec.tag, metadata: { ...spec.metadata }, contextId: spec.contextId ?? null, verified: spec.verified, liveNow: b.liveCount() });
170
+ await b.after("create");
171
+ return { id, tag: spec.tag };
172
+ },
173
+ async findByTag(tag, signal) {
174
+ await b.before("findByTag", signal);
175
+ const found = [...b.sessions.values()].filter((s) => s.tag === tag && s.state === "running");
176
+ b.record("findByTag", { tag, found: found.map((s) => s.id) });
177
+ await b.after("findByTag");
178
+ return found.map((s) => ({ id: s.id, tag: s.tag }));
179
+ },
180
+ async status(ref, signal) {
181
+ await b.before("status", signal);
182
+ const s = b.sessions.get(ref.id);
183
+ b.record("status", { id: ref.id });
184
+ await b.after("status");
185
+ return !s ? "gone" : s.state === "running" ? "running" : "stopped";
186
+ },
187
+ async attach(ref, signal) {
188
+ await b.before("attach", signal);
189
+ const s = b.sessions.get(ref.id);
190
+ if (!s)
191
+ throw new FakeProviderError(`no session ${ref.id}`, 404);
192
+ b.record("attach", { id: ref.id });
193
+ await b.after("attach");
194
+ return b.targetOf(s);
195
+ },
196
+ async release(ref, signal) {
197
+ await b.before("release", signal);
198
+ const s = b.sessions.get(ref.id);
199
+ const was = s?.state === "running";
200
+ if (s)
201
+ s.state = "stopped";
202
+ b.record(was ? "release" : "release-noop", { id: ref.id, tag: s?.tag ?? ref.tag });
203
+ await b.after("release");
204
+ },
205
+ async liveView(ref) {
206
+ const s = b.running(ref.id);
207
+ b.record("liveView", { id: ref.id });
208
+ if (!s)
209
+ return null;
210
+ const view = b.sentinels.bbLiveViewUrl;
211
+ return { fullscreen: view, framed: `${view}&framed=1`, pages: [{ id: "p1", url: s.url, title: b.pages[s.url]?.title ?? "", fullscreen: view }] };
212
+ },
213
+ async fetch(request, signal) {
214
+ await b.before("fetch", signal);
215
+ b.record("fetch", { url: request.url });
216
+ await b.after("fetch");
217
+ const entry = b.opts.fetches[request.url];
218
+ if (entry === undefined)
219
+ throw new FakeProviderError(`fetch ${request.url}: 404`, 404);
220
+ if (typeof entry === "string")
221
+ return { finalUrl: request.url, statusCode: 200, contentType: "text/markdown", content: entry };
222
+ const answer = entry[request.format === "raw" ? "raw" : "markdown"];
223
+ if (!answer || "status" in answer)
224
+ throw new FakeProviderError(`fetch ${request.url}: ${answer?.status ?? 404}`, answer?.status ?? 404);
225
+ return { finalUrl: request.url, statusCode: 200, contentType: answer.contentType, content: answer.content };
226
+ },
227
+ async search(request, signal) {
228
+ await b.before("search", signal);
229
+ b.record("search", { query: request.query });
230
+ await b.after("search");
231
+ return { results: b.opts.search.slice(0, request.n) };
232
+ },
233
+ downloads: {
234
+ async list(_ref) { return Object.entries(b.opts.downloads).map(([name, body]) => ({ name, sizeBytes: Buffer.byteLength(body), modifiedAt: null })); },
235
+ async read(_ref, fileName, maxBytes) {
236
+ const body = Buffer.from(b.opts.downloads[fileName] ?? "").subarray(0, maxBytes);
237
+ return (async function* () { yield body; })();
238
+ },
239
+ },
240
+ };
241
+ }
242
+ /** For a child's `remoteProvider` and `remoteDriver`; a held call stays open until the child dies. */
243
+ async serve() {
244
+ const faces = {
245
+ provider: this.provider,
246
+ broker: this.broker,
247
+ driver: this.driverFace,
248
+ };
249
+ const server = http.createServer((req, res) => {
250
+ let raw = "";
251
+ req.on("data", (c) => { raw += c; });
252
+ req.on("end", async () => {
253
+ const aborted = new AbortController();
254
+ res.on("close", () => { if (!res.writableEnded)
255
+ aborted.abort(); });
256
+ try {
257
+ const [face, method] = decodeURIComponent((req.url ?? "").replace(/^\/rpc\//, "")).split(".");
258
+ const fn = faces[face ?? ""]?.[method ?? ""];
259
+ if (typeof fn !== "function") {
260
+ res.writeHead(404).end(JSON.stringify({ error: { message: `no ${face}.${method}`, status: 404 } }));
261
+ return;
262
+ }
263
+ const args = raw ? JSON.parse(raw).args : [];
264
+ const result = await (face === "provider" ? fn.call(faces[face], ...args, aborted.signal) : fn.call(faces[face], ...args));
265
+ if (!res.writableEnded && !aborted.signal.aborted)
266
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ result: result ?? null }));
267
+ }
268
+ catch (error) {
269
+ if (aborted.signal.aborted)
270
+ return;
271
+ const e = error;
272
+ res.writeHead(e.status ?? 500, { "content-type": "application/json" }).end(JSON.stringify({ error: { message: e.message ?? String(error), status: e.status ?? 500 } }));
273
+ }
274
+ });
275
+ });
276
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
277
+ return {
278
+ url: `http://127.0.0.1:${server.address().port}`,
279
+ close: () => new Promise((resolve) => { server.closeAllConnections?.(); server.close(() => resolve()); }),
280
+ };
281
+ }
282
+ }
283
+ /** A held call never returns; an aborted one stops its request. */
284
+ export function remoteProvider(url, options = {}) {
285
+ const call = async (method, args, signal) => {
286
+ const res = await fetch(`${url}/rpc/provider.${method}`, { method: "POST", signal, headers: { "content-type": "application/json" }, body: JSON.stringify({ args }) });
287
+ const body = (await res.json());
288
+ if (body.error)
289
+ throw new FakeProviderError(body.error.message, body.error.status);
290
+ return body.result;
291
+ };
292
+ return {
293
+ name: options.name ?? "fake",
294
+ caps: { ...DEFAULT_CAPS, ...options.caps },
295
+ create: (spec, signal) => call("create", [spec], signal),
296
+ findByTag: (tag, signal) => call("findByTag", [tag], signal),
297
+ status: (ref, signal) => call("status", [ref], signal),
298
+ attach: (ref, signal) => call("attach", [ref], signal),
299
+ release: (ref, signal) => call("release", [ref], signal),
300
+ liveView: (ref) => call("liveView", [ref]),
301
+ fetch: (request, signal) => call("fetch", [request], signal),
302
+ search: (request, signal) => call("search", [request], signal),
303
+ };
304
+ }
305
+ /** Counts a fill before the provider is touched and never repeats an unknown one; its failures carry only codes. */
306
+ export class FakeBroker {
307
+ b;
308
+ constructor(b) {
309
+ this.b = b;
310
+ }
311
+ async connections() { return this.b.opts.connections; }
312
+ async acquire(name) {
313
+ await this.b.before("broker.acquire");
314
+ const id = this.b.newId("br");
315
+ const session = { id, tag: name, metadata: {}, state: "running", url: this.b.opts.connections.find((c) => c.name === name)?.startUrl ?? this.b.opts.start, broker: true, plane: name };
316
+ this.b.sessions.set(id, session);
317
+ this.b.noteLive();
318
+ this.b.record("broker.acquire", { id, name });
319
+ await this.b.after("broker.acquire");
320
+ return { session: id, attach: this.b.targetOf(session), leaseExpiresAt: new Date(Date.now() + 60_000).toISOString(), recording: false };
321
+ }
322
+ async heartbeat(session) {
323
+ await this.b.before("broker.heartbeat");
324
+ this.b.record("broker.heartbeat", { id: session });
325
+ return { leaseExpiresAt: new Date(Date.now() + 60_000).toISOString() };
326
+ }
327
+ async release(session) {
328
+ await this.b.before("broker.release");
329
+ const s = this.b.sessions.get(session);
330
+ if (s)
331
+ s.state = "stopped";
332
+ this.b.record("broker.release", { id: session });
333
+ await this.b.after("broker.release");
334
+ }
335
+ async fill(session, request) {
336
+ this.b.record("broker.fill", { id: session, pageUrl: request.pageUrl, fields: request.fields.map((f) => f.field) });
337
+ await this.b.before("broker.fill");
338
+ await this.b.after("broker.fill");
339
+ return { status: "completed", fields: request.fields.map((_f, index) => ({ index, status: "filled" })) };
340
+ }
341
+ async captureTotpSeed(session, request) {
342
+ this.b.record("broker.totp", { id: session, pageUrl: request.pageUrl });
343
+ await this.b.before("broker.totp");
344
+ return { stored: true, field: "otp" };
345
+ }
346
+ async downloads() { return Object.entries(this.b.opts.downloads).map(([name, body]) => ({ name, sizeBytes: Buffer.byteLength(body), modifiedAt: null })); }
347
+ }
348
+ export class FakeDriverFace {
349
+ b;
350
+ constructor(b) {
351
+ this.b = b;
352
+ }
353
+ session(id) {
354
+ const s = this.b.sessions.get(id);
355
+ if (!s || s.state !== "running")
356
+ throw new FakeProviderError(`session ${id} is not running`, 410);
357
+ return s;
358
+ }
359
+ pageOf(id) {
360
+ const url = this.session(id).url;
361
+ return this.b.pages[url] ?? fixturePage(url, "");
362
+ }
363
+ async call(id, op, knob, detail = {}) {
364
+ await this.b.before(`driver.${knob}`);
365
+ this.b.dispatched.push({ op, session: id, url: this.b.sessions.get(id)?.url ?? null, ...detail });
366
+ }
367
+ async connect(target) {
368
+ await this.b.before("driver.connect");
369
+ const id = new URL(target.sdkCdpUrl).searchParams.get("sessionId") ?? "";
370
+ this.session(id);
371
+ return id;
372
+ }
373
+ async snapshot(id) {
374
+ await this.call(id, "snapshot", "snapshot");
375
+ const out = `[0] main\n [1] text: ${this.pageOf(id).text}`;
376
+ await this.b.after("driver.snapshot");
377
+ return out;
378
+ }
379
+ /** A `goto` action moves the page; any other code returns what it was given. */
380
+ async run(id, input) {
381
+ await this.call(id, "run", "run", { input });
382
+ const go = input.actions?.find((action) => action.op === "goto");
383
+ if (go?.url)
384
+ this.session(id).url = go.url;
385
+ const out = input.actions ? { completed: input.actions.length, url: this.session(id).url } : { value: input.code };
386
+ await this.b.after("driver.run");
387
+ return out;
388
+ }
389
+ /** No `dispatched` row: a read of the URL is not a read of the page. */
390
+ async url(id) {
391
+ await this.b.before("driver.url");
392
+ return this.session(id).url;
393
+ }
394
+ /** Header-only image of the viewport (or full page) times the device scale; each capture is a dispatched row. */
395
+ async screenshot(id, options = {}) {
396
+ await this.call(id, "screenshot", "screenshot", { options });
397
+ const { viewport = { width: 1288, height: 711 }, fullPageHeight = 8319, deviceScale = 1 } = this.b.opts;
398
+ const factor = options.scale === "css" ? 1 : deviceScale;
399
+ const width = viewport.width * factor;
400
+ const height = (options.fullPage ? fullPageHeight : viewport.height) * factor;
401
+ const type = options.type ?? "jpeg";
402
+ await this.b.after("driver.screenshot");
403
+ return { data: fakeImage(type, width, height).toString("base64"), mimeType: `image/${type}`, width, height };
404
+ }
405
+ async page(id) {
406
+ await this.call(id, "read", "page");
407
+ const out = { ...this.pageOf(id) };
408
+ await this.b.after("driver.page");
409
+ return out;
410
+ }
411
+ async close(id) {
412
+ this.b.dispatched.push({ op: "close", session: id, url: null });
413
+ }
414
+ }
@@ -0,0 +1,28 @@
1
+ import type { AttachTarget } from "../core/host.js";
2
+ import { type FakeBackend, type FakeScreenshotOptions, type FixturePage } from "./backend.js";
3
+ export type FakeDriver = {
4
+ snapshot(): Promise<string>;
5
+ /** A `goto` action moves the page; any other code returns what it was given. */
6
+ run(input: {
7
+ code?: string;
8
+ actions?: Array<{
9
+ op: string;
10
+ url?: string;
11
+ [field: string]: unknown;
12
+ }>;
13
+ }): Promise<unknown>;
14
+ /** The page's URL without a `read` row. */
15
+ url(): Promise<string>;
16
+ screenshot(options?: FakeScreenshotOptions): Promise<{
17
+ data: string;
18
+ mimeType: string;
19
+ width: number;
20
+ height: number;
21
+ }>;
22
+ page(): Promise<FixturePage>;
23
+ close(): Promise<void>;
24
+ };
25
+ export type FakeDriverFactory = (target: AttachTarget) => Promise<FakeDriver>;
26
+ export declare function fakeDriver(b: FakeBackend): FakeDriverFactory;
27
+ /** A held op never returns. */
28
+ export declare function remoteDriver(url: string): FakeDriverFactory;