@lunora/browser 1.0.0-alpha.3 → 1.0.0-alpha.30

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.
package/LICENSE.md CHANGED
@@ -103,3 +103,9 @@ Unless required by applicable law or agreed to in writing, software distributed
103
103
  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
104
104
  CONDITIONS OF ANY KIND, either express or implied. See the License for the
105
105
  specific language governing permissions and limitations under the License.
106
+
107
+ <!-- DEPENDENCIES -->
108
+ <!-- /DEPENDENCIES -->
109
+
110
+ <!-- TYPE_DEPENDENCIES -->
111
+ <!-- /TYPE_DEPENDENCIES -->
package/README.md CHANGED
@@ -10,6 +10,8 @@
10
10
 
11
11
  <!-- END_PACKAGE_OG_IMAGE_PLACEHOLDER -->
12
12
 
13
+ > **Experimental** — this package is outside the Lunora 1.0 stability promise: its API may change in any release, without a major version bump.
14
+
13
15
  <br />
14
16
 
15
17
  <div align="center">
package/dist/index.d.mts CHANGED
@@ -1,25 +1,28 @@
1
1
  /**
2
- * Structural projection of the Cloudflare **Browser Rendering** binding
3
- * (`env.BROWSER`). The binding is a `Fetcher` under the hood — `@cloudflare/playwright`
4
- * drives it via `launch(env.BROWSER)`. Declared locally (an empty structural
5
- * marker) so unit tests can pass a plain-object double and the real binding
6
- * satisfies the same shape without importing `@cloudflare/workers-types` into
7
- * the public surface. See https://developers.cloudflare.com/browser-rendering/.
8
- *
9
- * It is intentionally opaque: callers never touch the binding directly, they
10
- * hand it to {@link LunoraBrowserOptions.binding} and the Playwright layer
11
- * consumes it. Typed as a non-empty marker so an arbitrary value (e.g. `{}`)
12
- * doesn't silently type-check where a binding is required.
13
- */
2
+ * Structural projection of the Cloudflare **Browser Rendering** binding
3
+ * (`env.BROWSER`). The binding is a `Fetcher` under the hood — `@cloudflare/playwright`
4
+ * drives it via `launch(env.BROWSER)`. Declared locally (an empty structural
5
+ * marker) so unit tests can pass a plain-object double and the real binding
6
+ * satisfies the same shape without importing `@cloudflare/workers-types` into
7
+ * the public surface. See https://developers.cloudflare.com/browser-rendering/.
8
+ *
9
+ * It is intentionally opaque: callers never touch the binding directly, they
10
+ * hand it to {@link LunoraBrowserOptions.binding} and the Playwright layer
11
+ * consumes it. `fetch` is REQUIRED (the real binding is a `Fetcher`, so it
12
+ * always has one) so the marker actually excludes an arbitrary value like `{}` —
13
+ * a bare object fails to type-check where a binding is required, catching the
14
+ * misuse at the call site instead of deferring to an opaque launch error.
15
+ * @experimental
16
+ */
14
17
  interface BrowserBindingLike {
15
- readonly fetch?: (...args: never[]) => unknown;
18
+ readonly fetch: typeof fetch;
16
19
  }
17
20
  /**
18
- * Minimal projection of a Playwright `Route` (the argument the `page.route`
19
- * handler receives). Only the members the SSRF redirect guard drives are
20
- * declared: inspect the intercepted request's URL / navigation-ness, then either
21
- * let it proceed ({@link RouteLike.continue}) or reject it ({@link RouteLike.abort}).
22
- */
21
+ * Minimal projection of a Playwright `Route` (the argument the `page.route`
22
+ * handler receives). Only the members the SSRF redirect guard drives are
23
+ * declared: inspect the intercepted request's URL / navigation-ness, then either
24
+ * let it proceed ({@link RouteLike.continue}) or reject it ({@link RouteLike.abort}).
25
+ */
23
26
  interface RouteLike {
24
27
  /** Reject the intercepted request (fail-closed); `errorCode` is a Playwright abort reason. */
25
28
  abort: (errorCode?: string) => Promise<void>;
@@ -32,28 +35,29 @@ interface RouteLike {
32
35
  };
33
36
  }
34
37
  /**
35
- * Minimal projection of a Playwright `Page` — just the methods the helpers drive.
36
- * Declared structurally so a test can inject a plain stub instead of a real
37
- * headless page (which needs workerd + the Browser Rendering binding).
38
- */
38
+ * Minimal projection of a Playwright `Page` — just the methods the helpers drive.
39
+ * Declared structurally so a test can inject a plain stub instead of a real
40
+ * headless page (which needs workerd + the Browser Rendering binding).
41
+ * @experimental
42
+ */
39
43
  interface PageLike {
40
44
  /** Return the page's serialized HTML after the navigation settles. */
41
45
  content: () => Promise<string>;
42
46
  /** Run a function in the page context and return its (serializable) result. */
43
- evaluate: <T>(function_: (...args: never[]) => T) => Promise<T>;
47
+ evaluate: <T>(function_: () => T) => Promise<T>;
44
48
  /** Navigate to a URL; resolves once the configured wait condition is met. */
45
49
  goto: (url: string, options?: {
46
50
  timeout?: number;
47
- waitUntil?: string;
51
+ waitUntil?: "commit" | "domcontentloaded" | "load" | "networkidle";
48
52
  }) => Promise<unknown>;
49
53
  /** Render the page to a PDF buffer. */
50
54
  pdf: (options?: Record<string, unknown>) => Promise<Uint8Array>;
51
55
  /**
52
- * Register a request interceptor (Playwright `page.route`). Optional: a fake
53
- * or older page double without it still works — the SSRF redirect guard only
54
- * activates when interception is available, and the initial-URL guard applies
55
- * regardless. `pattern` follows Playwright's glob/URL matcher.
56
- */
56
+ * Register a request interceptor (Playwright `page.route`). Optional: a fake
57
+ * or older page double without it still works — the SSRF redirect guard only
58
+ * activates when interception is available, and the initial-URL guard applies
59
+ * regardless. `pattern` follows Playwright's glob/URL matcher.
60
+ */
57
61
  route?: (pattern: string, handler: (route: RouteLike) => unknown) => Promise<void>;
58
62
  /** Render the page to a PNG/JPEG buffer. */
59
63
  screenshot: (options?: Record<string, unknown>) => Promise<Uint8Array>;
@@ -64,154 +68,264 @@ interface PageLike {
64
68
  }) => Promise<void>;
65
69
  }
66
70
  /**
67
- * Minimal projection of a Playwright `BrowserContext`. Only `newPage` is used;
68
- * declared structurally for the same test-double reason as {@link PageLike}.
69
- */
71
+ * Minimal projection of a Playwright `BrowserContext`. Only `newPage` is used;
72
+ * declared structurally for the same test-double reason as {@link PageLike}.
73
+ * @experimental
74
+ */
70
75
  interface BrowserContextLike {
71
76
  newPage: () => Promise<PageLike>;
72
77
  }
73
78
  /**
74
- * Minimal projection of a Playwright `Browser` (the value `launch` resolves to).
75
- * Only `newContext`/`close` are used; declared structurally for the same
76
- * test-double reason as {@link PageLike}.
77
- */
79
+ * Minimal projection of a Playwright `Browser` (the value `launch` resolves to).
80
+ * Only `newContext`/`close` are used; declared structurally for the same
81
+ * test-double reason as {@link PageLike}.
82
+ * @experimental
83
+ */
78
84
  interface BrowserLike {
79
85
  close: () => Promise<void>;
80
86
  newContext: () => Promise<BrowserContextLike>;
87
+ /**
88
+ * The Browser Rendering session this browser is attached to, when the
89
+ * runtime exposes it.
90
+ *
91
+ * Optional because this is a structural projection, not a re-declaration of
92
+ * the upstream Playwright type — but without it there is no way to learn
93
+ * the id of a session you just held open with `launch(fn, { keepAlive })`,
94
+ * which makes {@link Browser.connect} unreachable except by guessing from
95
+ * {@link Browser.sessions}.
96
+ */
97
+ sessionId?: () => string | undefined;
81
98
  }
82
99
  /**
83
- * Structural projection of `@cloudflare/playwright`'s `launch` export
84
- * (`import { launch } from "@cloudflare/playwright"`). Injected via
85
- * {@link LunoraBrowserOptions.launch} so the factory never imports
86
- * `@cloudflare/playwright` at module top — that keeps the heavy optional peer
87
- * dep out of the bundle for apps that never screenshot, and lets tests pass a
88
- * fake. Calling it with the Browser Rendering binding resolves a {@link BrowserLike}.
89
- */
100
+ * Structural projection of `@cloudflare/playwright`'s `launch` export
101
+ * (`import { launch } from "@cloudflare/playwright"`). Injected via
102
+ * {@link LunoraBrowserOptions.launch} so the factory never imports
103
+ * `@cloudflare/playwright` at module top — that keeps the heavy optional peer
104
+ * dep out of the bundle for apps that never screenshot, and lets tests pass a
105
+ * fake. Calling it with the Browser Rendering binding resolves a {@link BrowserLike}.
106
+ * @experimental
107
+ */
90
108
  type BrowserLaunchLike = (binding: BrowserBindingLike, options?: Record<string, unknown>) => Promise<BrowserLike>;
91
- /** Options shared by the page-driving helpers ({@link Browser.screenshot} etc.). */
109
+ /**
110
+ * One live Browser Rendering session, as `@cloudflare/playwright`'s `sessions()`
111
+ * reports it. `connectionId` is set while another worker holds the session — you
112
+ * can only {@link Browser.connect} to a free one.
113
+ * @experimental
114
+ */
115
+ interface BrowserSession {
116
+ connectionId?: string;
117
+ sessionId: string;
118
+ startTime?: number;
119
+ }
120
+ /**
121
+ * Structural projection of `@cloudflare/playwright`'s `connect` export —
122
+ * re-attaches to an existing session rather than starting a new browser.
123
+ * Injected like {@link BrowserLaunchLike} so the peer dep stays optional.
124
+ * @experimental
125
+ */
126
+ type BrowserConnectLike = (binding: BrowserBindingLike, sessionId: string) => Promise<BrowserLike>;
127
+ /**
128
+ * Structural projection of `@cloudflare/playwright`'s `sessions` export — lists
129
+ * the account's live Browser Rendering sessions for this binding.
130
+ * @experimental
131
+ */
132
+ type BrowserSessionsLike = (binding: BrowserBindingLike) => Promise<ReadonlyArray<BrowserSession>>;
133
+ /**
134
+ * Options shared by the page-driving helpers ({@link Browser.screenshot} etc.).
135
+ * @experimental
136
+ */
92
137
  interface NavigateOptions {
93
138
  /**
94
- * Hard timeout in milliseconds for the navigation + operation. Clamped to a
95
- * sane ceiling so a hung/hostile page can't pin the worker. Default 30000.
96
- */
139
+ * Hard timeout in milliseconds for the navigation + operation. Clamped to a
140
+ * sane ceiling so a hung/hostile page can't pin the worker. Default 30000.
141
+ */
97
142
  timeoutMs?: number;
98
143
  /**
99
- * Playwright navigation wait condition. Playwright's set differs from
100
- * Puppeteer's: `load`, `domcontentloaded`, `networkidle`, `commit`.
101
- * Default `load`.
102
- */
144
+ * Playwright navigation wait condition. Playwright's set differs from
145
+ * Puppeteer's: `load`, `domcontentloaded`, `networkidle`, `commit`.
146
+ * Default `load`.
147
+ */
103
148
  waitUntil?: "commit" | "domcontentloaded" | "load" | "networkidle";
104
149
  }
105
- /** Options for {@link Browser.screenshot}. */
150
+ /**
151
+ * Options for {@link Browser.screenshot}.
152
+ * @experimental
153
+ */
106
154
  interface ScreenshotOptions extends NavigateOptions {
107
155
  /** Capture the full scrollable page rather than just the viewport. */
108
156
  fullPage?: boolean;
109
157
  /** Image encoding. Default `png`. */
110
158
  type?: "jpeg" | "png";
111
159
  /**
112
- * Viewport size. Each dimension is hard-capped (see the factory's
113
- * `MAX_VIEWPORT_*`) so a caller can't request a multi-million-pixel render.
114
- */
160
+ * Viewport size. Each dimension is hard-capped (see the factory's
161
+ * `MAX_VIEWPORT_*`) so a caller can't request a multi-million-pixel render.
162
+ */
115
163
  viewport?: {
116
164
  height: number;
117
165
  width: number;
118
166
  };
119
167
  }
120
- /** Options for {@link Browser.pdf}. */
168
+ /**
169
+ * Options for {@link Browser.pdf}.
170
+ * @experimental
171
+ */
121
172
  interface PdfOptions extends NavigateOptions {
122
173
  /** Paper format (`A4`, `Letter`, …) forwarded to Playwright. */
123
174
  format?: string;
124
175
  /** Print background graphics. Default `false`. */
125
176
  printBackground?: boolean;
126
177
  /**
127
- * Viewport used while laying out the page before printing. Hard-capped like
128
- * {@link ScreenshotOptions.viewport}.
129
- */
178
+ * Viewport used while laying out the page before printing. Hard-capped like
179
+ * {@link ScreenshotOptions.viewport}.
180
+ */
130
181
  viewport?: {
131
182
  height: number;
132
183
  width: number;
133
184
  };
134
185
  }
186
+ /**
187
+ * `LunoraBrowserOptions` is part of the experimental `@lunora/browser` API and may change without a major version bump.
188
+ * @experimental
189
+ */
135
190
  interface LunoraBrowserOptions {
136
191
  /**
137
- * Strict host allowlist. When set (non-empty), a navigation URL is refused
138
- * unless its hostname exactly matches one of these entries (case-insensitive,
139
- * trailing-dot-normalized, IPv6 brackets stripped). This is the only guard
140
- * that fully closes DNS rebinding: a public hostname that resolves to a
141
- * private/metadata IP can still be pinned out if it isn't on the list. Set it
142
- * whenever you pass client-controlled URLs to the browser. Leave it unset (the
143
- * default) to keep the previous behavior (only the string-based SSRF guard).
144
- */
192
+ * Strict host allowlist. When set (non-empty), a navigation URL is refused
193
+ * unless its hostname exactly matches one of these entries (case-insensitive,
194
+ * trailing-dot-normalized, IPv6 brackets stripped). This is the only guard
195
+ * that fully closes DNS rebinding: a public hostname that resolves to a
196
+ * private/metadata IP can still be pinned out if it isn't on the list. Set it
197
+ * whenever you pass client-controlled URLs to the browser. Leave it unset (the
198
+ * default) to keep the previous behavior (only the string-based SSRF guard).
199
+ */
145
200
  allowedHosts?: string[];
146
201
  /**
147
- * Opt out of the SSRF guard that, by default, refuses to navigate to a
148
- * private / internal / loopback / link-local host (RFC1918, `127.0.0.0/8`,
149
- * `169.254.0.0/16` incl. the cloud-metadata address, CGNAT, IPv6 ULA/
150
- * link-local, and `localhost` / `*.internal` / `*.local` literals). Leave it
151
- * `false` (the default) unless every caller-supplied URL is trusted — e.g.
152
- * you deliberately drive the browser at an internal service reachable through
153
- * a Cloudflare Tunnel / private-network binding. Setting it `true` re-opens
154
- * the SSRF surface, so never combine it with caller-controlled URLs.
155
- */
202
+ * Opt out of the SSRF guard that, by default, refuses to navigate to a
203
+ * private / internal / loopback / link-local host (RFC1918, `127.0.0.0/8`,
204
+ * `169.254.0.0/16` incl. the cloud-metadata address, CGNAT, IPv6 ULA/
205
+ * link-local, and `localhost` / `*.internal` / `*.local` literals). Leave it
206
+ * `false` (the default) unless every caller-supplied URL is trusted — e.g.
207
+ * you deliberately drive the browser at an internal service reachable through
208
+ * a Cloudflare Tunnel / private-network binding. Setting it `true` re-opens
209
+ * the SSRF surface, so never combine it with caller-controlled URLs.
210
+ */
156
211
  allowPrivateTargets?: boolean;
157
212
  /** The Cloudflare Browser Rendering binding (`env.BROWSER`). Required. */
158
213
  binding: BrowserBindingLike;
159
214
  /**
160
- * The `@cloudflare/playwright` `launch` function. Injected rather than
161
- * imported at module top so the optional peer dep stays out of the bundle
162
- * for non-browser apps and tests can pass a double. The generated worker
163
- * passes the real function; omitting it makes the helper throw on first use
164
- * with a clear "install `@cloudflare/playwright`" error.
165
- */
215
+ * The `@cloudflare/playwright` `connect` function, injected like
216
+ * {@link LunoraBrowserOptions.launch}. Required for {@link Browser.connect}.
217
+ */
218
+ connect?: BrowserConnectLike;
219
+ /**
220
+ * The `@cloudflare/playwright` `launch` function. Injected rather than
221
+ * imported at module top so the optional peer dep stays out of the bundle
222
+ * for non-browser apps and tests can pass a double. The generated worker
223
+ * passes the real function; omitting it makes the helper throw on first use
224
+ * with a clear "install `@cloudflare/playwright`" error.
225
+ */
166
226
  launch?: BrowserLaunchLike;
167
227
  /**
168
- * Best-effort DNS-rebinding re-check. When `true` (and `allowPrivateTargets`
169
- * is `false`), the factory resolves the URL's hostname over Cloudflare DoH
170
- * (`https://cloudflare-dns.com/dns-query`) and refuses to navigate if any
171
- * resolved A/AAAA record is a private/internal address — closing the gap
172
- * where a public hostname resolves to a private IP after the string guard
173
- * passes. Off by default: it adds a DNS round-trip and is TOCTOU-imperfect
174
- * (the browser re-resolves independently). If the DoH lookup itself fails, it
175
- * falls back to the string guard rather than allowing a resolved private IP.
176
- * For a hard guarantee prefer {@link LunoraBrowserOptions.allowedHosts}.
177
- */
228
+ * Best-effort DNS-rebinding re-check. When `true` (and `allowPrivateTargets`
229
+ * is `false`), the factory resolves the URL's hostname over Cloudflare DoH
230
+ * (`https://cloudflare-dns.com/dns-query`) and refuses to navigate if any
231
+ * resolved A/AAAA record is a private/internal address — closing the gap
232
+ * where a public hostname resolves to a private IP after the string guard
233
+ * passes.
234
+ *
235
+ * **On by default when no {@link LunoraBrowserOptions.allowedHosts} is set**,
236
+ * because a `scrape`/`screenshot` action that forwards a client-supplied URL
237
+ * is the common shape and the string guard alone lets
238
+ * `http://127.0.0.1.nip.io:8787/…` through to an internal service. It costs
239
+ * one DNS round-trip per navigation and is TOCTOU-imperfect (the browser
240
+ * re-resolves independently), and if the DoH lookup itself fails it falls
241
+ * back to the string guard rather than allowing a resolved private IP.
242
+ *
243
+ * Configuring `allowedHosts` turns it OFF by default: an exact-origin
244
+ * allowlist is the stronger guard and may deliberately name an internal host
245
+ * (reachable over a Tunnel / private-network binding) that a resolved-address
246
+ * check would refuse. Set this explicitly to `true` to run both, or to
247
+ * `false` for trusted, non-caller-supplied URLs where the round-trip matters.
248
+ */
178
249
  resolveDns?: boolean;
179
250
  /**
180
- * Default navigation timeout (ms) applied when a per-call `timeoutMs` is not
181
- * given. Clamped to the factory's `MAX_TIMEOUT_MS`. Default 30000.
182
- */
251
+ * The `@cloudflare/playwright` `sessions` function, injected like
252
+ * {@link LunoraBrowserOptions.launch}. Required for {@link Browser.sessions}.
253
+ */
254
+ sessions?: BrowserSessionsLike;
255
+ /**
256
+ * Default navigation timeout (ms) applied when a per-call `timeoutMs` is not
257
+ * given. Clamped to the factory's `MAX_TIMEOUT_MS`. Default 30000.
258
+ */
183
259
  timeoutMs?: number;
184
260
  }
185
261
  /**
186
- * The `ctx.browser` surface — Cloudflare Browser Rendering driven through
187
- * `@cloudflare/playwright`. **Action-only**: every method performs
188
- * non-deterministic network I/O (it navigates a real headless browser to a
189
- * URL), so codegen wires it onto `ActionCtx` exclusively — never `QueryCtx`/
190
- * `MutationCtx` — exactly like `ctx.ai` / `ctx.fetch`. Each helper launches a
191
- * browser, opens a context + page, navigates, performs the op, and always
192
- * closes the browser in a `finally` (a leaked session is billed and
193
- * rate-limited).
194
- */
262
+ * The `ctx.browser` surface — Cloudflare Browser Rendering driven through
263
+ * `@cloudflare/playwright`. **Action-only**: every method performs
264
+ * non-deterministic network I/O (it navigates a real headless browser to a
265
+ * URL), so codegen wires it onto `ActionCtx` exclusively — never `QueryCtx`/
266
+ * `MutationCtx` — exactly like `ctx.ai` / `ctx.fetch`. Each helper launches a
267
+ * browser, opens a context + page, navigates, performs the op, and always
268
+ * closes the browser in a `finally` (a leaked session is billed and
269
+ * rate-limited).
270
+ * @experimental
271
+ */
195
272
  interface Browser {
273
+ /**
274
+ * Re-attach to an existing session and hand the browser to `fn`.
275
+ *
276
+ * Get the id either by reading it inside the call that opened the session
277
+ * (`launch(async (browser) => browser.sessionId?.(), { keepAlive: 600 })`)
278
+ * and persisting it, or by picking a free one out of
279
+ * {@link Browser.sessions} — an entry with a `connectionId` is already held
280
+ * by another worker.
281
+ *
282
+ * The session is deliberately **left open** afterwards — closing it is the
283
+ * whole thing you are avoiding. Close it when the flow is done by passing
284
+ * `close: true`, or let `keepAlive` lapse.
285
+ *
286
+ * This is what makes agent-style browsing possible: a model calls
287
+ * `navigate`, then `click`, then `extract` as three separate action
288
+ * invocations, and the page has to survive between them. With only the
289
+ * per-call lifecycle each step got a fresh browser, so `click` ran against
290
+ * a blank page — silently, which is the worst shape for that bug.
291
+ */
292
+ connect: <T>(sessionId: string, function_: (browser: BrowserLike) => Promise<T>, options?: {
293
+ close?: boolean;
294
+ }) => Promise<T>;
196
295
  /** Serialized HTML of `url` after navigation settles. */
197
296
  content: (url: string, options?: NavigateOptions) => Promise<string>;
198
297
  /**
199
- * Low-level escape hatch: launch a raw Playwright `Browser` and hand it to
200
- * `fn` (e.g. for multi-page flows or APIs not surfaced here). The browser is
201
- * **always closed** when `fn` resolves or throws — do not retain references
202
- * to it past the callback.
203
- */
204
- launch: <T>(function_: (browser: BrowserLike) => Promise<T>) => Promise<T>;
298
+ * Low-level escape hatch: launch a raw Playwright `Browser` and hand it to
299
+ * `fn` (e.g. for multi-page flows or APIs not surfaced here).
300
+ *
301
+ * The browser is **always closed** when `fn` resolves or throws — unless
302
+ * `keepAlive` is set, which holds the session open for that many seconds so
303
+ * a later {@link Browser.connect} can re-attach. Do not retain references to
304
+ * the browser past the callback either way.
305
+ */
306
+ launch: <T>(function_: (browser: BrowserLike) => Promise<T>, options?: {
307
+ keepAlive?: number;
308
+ }) => Promise<T>;
205
309
  /** Render `url` to a PDF buffer. */
206
310
  pdf: (url: string, options?: PdfOptions) => Promise<Uint8Array>;
207
311
  /**
208
- * Navigate to `url`, run `fn` inside the page context, and return its
209
- * (serializable) result. `fn` runs in the browser, not the worker — it
210
- * cannot close over worker-side variables.
211
- */
312
+ * Navigate to `url`, run `fn` inside the page context, and return its
313
+ * (serializable) result. `fn` runs in the browser, not the worker — it
314
+ * cannot close over worker-side variables.
315
+ */
212
316
  scrape: <T>(url: string, function_: (...args: never[]) => T, options?: NavigateOptions) => Promise<T>;
213
317
  /** Render `url` to an image buffer (PNG by default). */
214
318
  screenshot: (url: string, options?: ScreenshotOptions) => Promise<Uint8Array>;
319
+ /**
320
+ * List the live Browser Rendering sessions for this binding, so a caller can
321
+ * pick a free one to {@link Browser.connect} to. An entry with a
322
+ * `connectionId` is already held by another worker.
323
+ */
324
+ sessions: () => Promise<ReadonlyArray<BrowserSession>>;
215
325
  }
326
+ /**
327
+ * `createBrowser` is part of the experimental `@lunora/browser` API and may change without a major version bump.
328
+ * @experimental
329
+ */
216
330
  declare const createBrowser: (options: LunoraBrowserOptions) => Browser;
217
331
  export { type Browser, type BrowserBindingLike, type BrowserContextLike, type BrowserLaunchLike, type BrowserLike, type LunoraBrowserOptions, type NavigateOptions, type PageLike, type PdfOptions, type ScreenshotOptions, createBrowser };
package/dist/index.d.ts CHANGED
@@ -1,25 +1,28 @@
1
1
  /**
2
- * Structural projection of the Cloudflare **Browser Rendering** binding
3
- * (`env.BROWSER`). The binding is a `Fetcher` under the hood — `@cloudflare/playwright`
4
- * drives it via `launch(env.BROWSER)`. Declared locally (an empty structural
5
- * marker) so unit tests can pass a plain-object double and the real binding
6
- * satisfies the same shape without importing `@cloudflare/workers-types` into
7
- * the public surface. See https://developers.cloudflare.com/browser-rendering/.
8
- *
9
- * It is intentionally opaque: callers never touch the binding directly, they
10
- * hand it to {@link LunoraBrowserOptions.binding} and the Playwright layer
11
- * consumes it. Typed as a non-empty marker so an arbitrary value (e.g. `{}`)
12
- * doesn't silently type-check where a binding is required.
13
- */
2
+ * Structural projection of the Cloudflare **Browser Rendering** binding
3
+ * (`env.BROWSER`). The binding is a `Fetcher` under the hood — `@cloudflare/playwright`
4
+ * drives it via `launch(env.BROWSER)`. Declared locally (an empty structural
5
+ * marker) so unit tests can pass a plain-object double and the real binding
6
+ * satisfies the same shape without importing `@cloudflare/workers-types` into
7
+ * the public surface. See https://developers.cloudflare.com/browser-rendering/.
8
+ *
9
+ * It is intentionally opaque: callers never touch the binding directly, they
10
+ * hand it to {@link LunoraBrowserOptions.binding} and the Playwright layer
11
+ * consumes it. `fetch` is REQUIRED (the real binding is a `Fetcher`, so it
12
+ * always has one) so the marker actually excludes an arbitrary value like `{}` —
13
+ * a bare object fails to type-check where a binding is required, catching the
14
+ * misuse at the call site instead of deferring to an opaque launch error.
15
+ * @experimental
16
+ */
14
17
  interface BrowserBindingLike {
15
- readonly fetch?: (...args: never[]) => unknown;
18
+ readonly fetch: typeof fetch;
16
19
  }
17
20
  /**
18
- * Minimal projection of a Playwright `Route` (the argument the `page.route`
19
- * handler receives). Only the members the SSRF redirect guard drives are
20
- * declared: inspect the intercepted request's URL / navigation-ness, then either
21
- * let it proceed ({@link RouteLike.continue}) or reject it ({@link RouteLike.abort}).
22
- */
21
+ * Minimal projection of a Playwright `Route` (the argument the `page.route`
22
+ * handler receives). Only the members the SSRF redirect guard drives are
23
+ * declared: inspect the intercepted request's URL / navigation-ness, then either
24
+ * let it proceed ({@link RouteLike.continue}) or reject it ({@link RouteLike.abort}).
25
+ */
23
26
  interface RouteLike {
24
27
  /** Reject the intercepted request (fail-closed); `errorCode` is a Playwright abort reason. */
25
28
  abort: (errorCode?: string) => Promise<void>;
@@ -32,28 +35,29 @@ interface RouteLike {
32
35
  };
33
36
  }
34
37
  /**
35
- * Minimal projection of a Playwright `Page` — just the methods the helpers drive.
36
- * Declared structurally so a test can inject a plain stub instead of a real
37
- * headless page (which needs workerd + the Browser Rendering binding).
38
- */
38
+ * Minimal projection of a Playwright `Page` — just the methods the helpers drive.
39
+ * Declared structurally so a test can inject a plain stub instead of a real
40
+ * headless page (which needs workerd + the Browser Rendering binding).
41
+ * @experimental
42
+ */
39
43
  interface PageLike {
40
44
  /** Return the page's serialized HTML after the navigation settles. */
41
45
  content: () => Promise<string>;
42
46
  /** Run a function in the page context and return its (serializable) result. */
43
- evaluate: <T>(function_: (...args: never[]) => T) => Promise<T>;
47
+ evaluate: <T>(function_: () => T) => Promise<T>;
44
48
  /** Navigate to a URL; resolves once the configured wait condition is met. */
45
49
  goto: (url: string, options?: {
46
50
  timeout?: number;
47
- waitUntil?: string;
51
+ waitUntil?: "commit" | "domcontentloaded" | "load" | "networkidle";
48
52
  }) => Promise<unknown>;
49
53
  /** Render the page to a PDF buffer. */
50
54
  pdf: (options?: Record<string, unknown>) => Promise<Uint8Array>;
51
55
  /**
52
- * Register a request interceptor (Playwright `page.route`). Optional: a fake
53
- * or older page double without it still works — the SSRF redirect guard only
54
- * activates when interception is available, and the initial-URL guard applies
55
- * regardless. `pattern` follows Playwright's glob/URL matcher.
56
- */
56
+ * Register a request interceptor (Playwright `page.route`). Optional: a fake
57
+ * or older page double without it still works — the SSRF redirect guard only
58
+ * activates when interception is available, and the initial-URL guard applies
59
+ * regardless. `pattern` follows Playwright's glob/URL matcher.
60
+ */
57
61
  route?: (pattern: string, handler: (route: RouteLike) => unknown) => Promise<void>;
58
62
  /** Render the page to a PNG/JPEG buffer. */
59
63
  screenshot: (options?: Record<string, unknown>) => Promise<Uint8Array>;
@@ -64,154 +68,264 @@ interface PageLike {
64
68
  }) => Promise<void>;
65
69
  }
66
70
  /**
67
- * Minimal projection of a Playwright `BrowserContext`. Only `newPage` is used;
68
- * declared structurally for the same test-double reason as {@link PageLike}.
69
- */
71
+ * Minimal projection of a Playwright `BrowserContext`. Only `newPage` is used;
72
+ * declared structurally for the same test-double reason as {@link PageLike}.
73
+ * @experimental
74
+ */
70
75
  interface BrowserContextLike {
71
76
  newPage: () => Promise<PageLike>;
72
77
  }
73
78
  /**
74
- * Minimal projection of a Playwright `Browser` (the value `launch` resolves to).
75
- * Only `newContext`/`close` are used; declared structurally for the same
76
- * test-double reason as {@link PageLike}.
77
- */
79
+ * Minimal projection of a Playwright `Browser` (the value `launch` resolves to).
80
+ * Only `newContext`/`close` are used; declared structurally for the same
81
+ * test-double reason as {@link PageLike}.
82
+ * @experimental
83
+ */
78
84
  interface BrowserLike {
79
85
  close: () => Promise<void>;
80
86
  newContext: () => Promise<BrowserContextLike>;
87
+ /**
88
+ * The Browser Rendering session this browser is attached to, when the
89
+ * runtime exposes it.
90
+ *
91
+ * Optional because this is a structural projection, not a re-declaration of
92
+ * the upstream Playwright type — but without it there is no way to learn
93
+ * the id of a session you just held open with `launch(fn, { keepAlive })`,
94
+ * which makes {@link Browser.connect} unreachable except by guessing from
95
+ * {@link Browser.sessions}.
96
+ */
97
+ sessionId?: () => string | undefined;
81
98
  }
82
99
  /**
83
- * Structural projection of `@cloudflare/playwright`'s `launch` export
84
- * (`import { launch } from "@cloudflare/playwright"`). Injected via
85
- * {@link LunoraBrowserOptions.launch} so the factory never imports
86
- * `@cloudflare/playwright` at module top — that keeps the heavy optional peer
87
- * dep out of the bundle for apps that never screenshot, and lets tests pass a
88
- * fake. Calling it with the Browser Rendering binding resolves a {@link BrowserLike}.
89
- */
100
+ * Structural projection of `@cloudflare/playwright`'s `launch` export
101
+ * (`import { launch } from "@cloudflare/playwright"`). Injected via
102
+ * {@link LunoraBrowserOptions.launch} so the factory never imports
103
+ * `@cloudflare/playwright` at module top — that keeps the heavy optional peer
104
+ * dep out of the bundle for apps that never screenshot, and lets tests pass a
105
+ * fake. Calling it with the Browser Rendering binding resolves a {@link BrowserLike}.
106
+ * @experimental
107
+ */
90
108
  type BrowserLaunchLike = (binding: BrowserBindingLike, options?: Record<string, unknown>) => Promise<BrowserLike>;
91
- /** Options shared by the page-driving helpers ({@link Browser.screenshot} etc.). */
109
+ /**
110
+ * One live Browser Rendering session, as `@cloudflare/playwright`'s `sessions()`
111
+ * reports it. `connectionId` is set while another worker holds the session — you
112
+ * can only {@link Browser.connect} to a free one.
113
+ * @experimental
114
+ */
115
+ interface BrowserSession {
116
+ connectionId?: string;
117
+ sessionId: string;
118
+ startTime?: number;
119
+ }
120
+ /**
121
+ * Structural projection of `@cloudflare/playwright`'s `connect` export —
122
+ * re-attaches to an existing session rather than starting a new browser.
123
+ * Injected like {@link BrowserLaunchLike} so the peer dep stays optional.
124
+ * @experimental
125
+ */
126
+ type BrowserConnectLike = (binding: BrowserBindingLike, sessionId: string) => Promise<BrowserLike>;
127
+ /**
128
+ * Structural projection of `@cloudflare/playwright`'s `sessions` export — lists
129
+ * the account's live Browser Rendering sessions for this binding.
130
+ * @experimental
131
+ */
132
+ type BrowserSessionsLike = (binding: BrowserBindingLike) => Promise<ReadonlyArray<BrowserSession>>;
133
+ /**
134
+ * Options shared by the page-driving helpers ({@link Browser.screenshot} etc.).
135
+ * @experimental
136
+ */
92
137
  interface NavigateOptions {
93
138
  /**
94
- * Hard timeout in milliseconds for the navigation + operation. Clamped to a
95
- * sane ceiling so a hung/hostile page can't pin the worker. Default 30000.
96
- */
139
+ * Hard timeout in milliseconds for the navigation + operation. Clamped to a
140
+ * sane ceiling so a hung/hostile page can't pin the worker. Default 30000.
141
+ */
97
142
  timeoutMs?: number;
98
143
  /**
99
- * Playwright navigation wait condition. Playwright's set differs from
100
- * Puppeteer's: `load`, `domcontentloaded`, `networkidle`, `commit`.
101
- * Default `load`.
102
- */
144
+ * Playwright navigation wait condition. Playwright's set differs from
145
+ * Puppeteer's: `load`, `domcontentloaded`, `networkidle`, `commit`.
146
+ * Default `load`.
147
+ */
103
148
  waitUntil?: "commit" | "domcontentloaded" | "load" | "networkidle";
104
149
  }
105
- /** Options for {@link Browser.screenshot}. */
150
+ /**
151
+ * Options for {@link Browser.screenshot}.
152
+ * @experimental
153
+ */
106
154
  interface ScreenshotOptions extends NavigateOptions {
107
155
  /** Capture the full scrollable page rather than just the viewport. */
108
156
  fullPage?: boolean;
109
157
  /** Image encoding. Default `png`. */
110
158
  type?: "jpeg" | "png";
111
159
  /**
112
- * Viewport size. Each dimension is hard-capped (see the factory's
113
- * `MAX_VIEWPORT_*`) so a caller can't request a multi-million-pixel render.
114
- */
160
+ * Viewport size. Each dimension is hard-capped (see the factory's
161
+ * `MAX_VIEWPORT_*`) so a caller can't request a multi-million-pixel render.
162
+ */
115
163
  viewport?: {
116
164
  height: number;
117
165
  width: number;
118
166
  };
119
167
  }
120
- /** Options for {@link Browser.pdf}. */
168
+ /**
169
+ * Options for {@link Browser.pdf}.
170
+ * @experimental
171
+ */
121
172
  interface PdfOptions extends NavigateOptions {
122
173
  /** Paper format (`A4`, `Letter`, …) forwarded to Playwright. */
123
174
  format?: string;
124
175
  /** Print background graphics. Default `false`. */
125
176
  printBackground?: boolean;
126
177
  /**
127
- * Viewport used while laying out the page before printing. Hard-capped like
128
- * {@link ScreenshotOptions.viewport}.
129
- */
178
+ * Viewport used while laying out the page before printing. Hard-capped like
179
+ * {@link ScreenshotOptions.viewport}.
180
+ */
130
181
  viewport?: {
131
182
  height: number;
132
183
  width: number;
133
184
  };
134
185
  }
186
+ /**
187
+ * `LunoraBrowserOptions` is part of the experimental `@lunora/browser` API and may change without a major version bump.
188
+ * @experimental
189
+ */
135
190
  interface LunoraBrowserOptions {
136
191
  /**
137
- * Strict host allowlist. When set (non-empty), a navigation URL is refused
138
- * unless its hostname exactly matches one of these entries (case-insensitive,
139
- * trailing-dot-normalized, IPv6 brackets stripped). This is the only guard
140
- * that fully closes DNS rebinding: a public hostname that resolves to a
141
- * private/metadata IP can still be pinned out if it isn't on the list. Set it
142
- * whenever you pass client-controlled URLs to the browser. Leave it unset (the
143
- * default) to keep the previous behavior (only the string-based SSRF guard).
144
- */
192
+ * Strict host allowlist. When set (non-empty), a navigation URL is refused
193
+ * unless its hostname exactly matches one of these entries (case-insensitive,
194
+ * trailing-dot-normalized, IPv6 brackets stripped). This is the only guard
195
+ * that fully closes DNS rebinding: a public hostname that resolves to a
196
+ * private/metadata IP can still be pinned out if it isn't on the list. Set it
197
+ * whenever you pass client-controlled URLs to the browser. Leave it unset (the
198
+ * default) to keep the previous behavior (only the string-based SSRF guard).
199
+ */
145
200
  allowedHosts?: string[];
146
201
  /**
147
- * Opt out of the SSRF guard that, by default, refuses to navigate to a
148
- * private / internal / loopback / link-local host (RFC1918, `127.0.0.0/8`,
149
- * `169.254.0.0/16` incl. the cloud-metadata address, CGNAT, IPv6 ULA/
150
- * link-local, and `localhost` / `*.internal` / `*.local` literals). Leave it
151
- * `false` (the default) unless every caller-supplied URL is trusted — e.g.
152
- * you deliberately drive the browser at an internal service reachable through
153
- * a Cloudflare Tunnel / private-network binding. Setting it `true` re-opens
154
- * the SSRF surface, so never combine it with caller-controlled URLs.
155
- */
202
+ * Opt out of the SSRF guard that, by default, refuses to navigate to a
203
+ * private / internal / loopback / link-local host (RFC1918, `127.0.0.0/8`,
204
+ * `169.254.0.0/16` incl. the cloud-metadata address, CGNAT, IPv6 ULA/
205
+ * link-local, and `localhost` / `*.internal` / `*.local` literals). Leave it
206
+ * `false` (the default) unless every caller-supplied URL is trusted — e.g.
207
+ * you deliberately drive the browser at an internal service reachable through
208
+ * a Cloudflare Tunnel / private-network binding. Setting it `true` re-opens
209
+ * the SSRF surface, so never combine it with caller-controlled URLs.
210
+ */
156
211
  allowPrivateTargets?: boolean;
157
212
  /** The Cloudflare Browser Rendering binding (`env.BROWSER`). Required. */
158
213
  binding: BrowserBindingLike;
159
214
  /**
160
- * The `@cloudflare/playwright` `launch` function. Injected rather than
161
- * imported at module top so the optional peer dep stays out of the bundle
162
- * for non-browser apps and tests can pass a double. The generated worker
163
- * passes the real function; omitting it makes the helper throw on first use
164
- * with a clear "install `@cloudflare/playwright`" error.
165
- */
215
+ * The `@cloudflare/playwright` `connect` function, injected like
216
+ * {@link LunoraBrowserOptions.launch}. Required for {@link Browser.connect}.
217
+ */
218
+ connect?: BrowserConnectLike;
219
+ /**
220
+ * The `@cloudflare/playwright` `launch` function. Injected rather than
221
+ * imported at module top so the optional peer dep stays out of the bundle
222
+ * for non-browser apps and tests can pass a double. The generated worker
223
+ * passes the real function; omitting it makes the helper throw on first use
224
+ * with a clear "install `@cloudflare/playwright`" error.
225
+ */
166
226
  launch?: BrowserLaunchLike;
167
227
  /**
168
- * Best-effort DNS-rebinding re-check. When `true` (and `allowPrivateTargets`
169
- * is `false`), the factory resolves the URL's hostname over Cloudflare DoH
170
- * (`https://cloudflare-dns.com/dns-query`) and refuses to navigate if any
171
- * resolved A/AAAA record is a private/internal address — closing the gap
172
- * where a public hostname resolves to a private IP after the string guard
173
- * passes. Off by default: it adds a DNS round-trip and is TOCTOU-imperfect
174
- * (the browser re-resolves independently). If the DoH lookup itself fails, it
175
- * falls back to the string guard rather than allowing a resolved private IP.
176
- * For a hard guarantee prefer {@link LunoraBrowserOptions.allowedHosts}.
177
- */
228
+ * Best-effort DNS-rebinding re-check. When `true` (and `allowPrivateTargets`
229
+ * is `false`), the factory resolves the URL's hostname over Cloudflare DoH
230
+ * (`https://cloudflare-dns.com/dns-query`) and refuses to navigate if any
231
+ * resolved A/AAAA record is a private/internal address — closing the gap
232
+ * where a public hostname resolves to a private IP after the string guard
233
+ * passes.
234
+ *
235
+ * **On by default when no {@link LunoraBrowserOptions.allowedHosts} is set**,
236
+ * because a `scrape`/`screenshot` action that forwards a client-supplied URL
237
+ * is the common shape and the string guard alone lets
238
+ * `http://127.0.0.1.nip.io:8787/…` through to an internal service. It costs
239
+ * one DNS round-trip per navigation and is TOCTOU-imperfect (the browser
240
+ * re-resolves independently), and if the DoH lookup itself fails it falls
241
+ * back to the string guard rather than allowing a resolved private IP.
242
+ *
243
+ * Configuring `allowedHosts` turns it OFF by default: an exact-origin
244
+ * allowlist is the stronger guard and may deliberately name an internal host
245
+ * (reachable over a Tunnel / private-network binding) that a resolved-address
246
+ * check would refuse. Set this explicitly to `true` to run both, or to
247
+ * `false` for trusted, non-caller-supplied URLs where the round-trip matters.
248
+ */
178
249
  resolveDns?: boolean;
179
250
  /**
180
- * Default navigation timeout (ms) applied when a per-call `timeoutMs` is not
181
- * given. Clamped to the factory's `MAX_TIMEOUT_MS`. Default 30000.
182
- */
251
+ * The `@cloudflare/playwright` `sessions` function, injected like
252
+ * {@link LunoraBrowserOptions.launch}. Required for {@link Browser.sessions}.
253
+ */
254
+ sessions?: BrowserSessionsLike;
255
+ /**
256
+ * Default navigation timeout (ms) applied when a per-call `timeoutMs` is not
257
+ * given. Clamped to the factory's `MAX_TIMEOUT_MS`. Default 30000.
258
+ */
183
259
  timeoutMs?: number;
184
260
  }
185
261
  /**
186
- * The `ctx.browser` surface — Cloudflare Browser Rendering driven through
187
- * `@cloudflare/playwright`. **Action-only**: every method performs
188
- * non-deterministic network I/O (it navigates a real headless browser to a
189
- * URL), so codegen wires it onto `ActionCtx` exclusively — never `QueryCtx`/
190
- * `MutationCtx` — exactly like `ctx.ai` / `ctx.fetch`. Each helper launches a
191
- * browser, opens a context + page, navigates, performs the op, and always
192
- * closes the browser in a `finally` (a leaked session is billed and
193
- * rate-limited).
194
- */
262
+ * The `ctx.browser` surface — Cloudflare Browser Rendering driven through
263
+ * `@cloudflare/playwright`. **Action-only**: every method performs
264
+ * non-deterministic network I/O (it navigates a real headless browser to a
265
+ * URL), so codegen wires it onto `ActionCtx` exclusively — never `QueryCtx`/
266
+ * `MutationCtx` — exactly like `ctx.ai` / `ctx.fetch`. Each helper launches a
267
+ * browser, opens a context + page, navigates, performs the op, and always
268
+ * closes the browser in a `finally` (a leaked session is billed and
269
+ * rate-limited).
270
+ * @experimental
271
+ */
195
272
  interface Browser {
273
+ /**
274
+ * Re-attach to an existing session and hand the browser to `fn`.
275
+ *
276
+ * Get the id either by reading it inside the call that opened the session
277
+ * (`launch(async (browser) => browser.sessionId?.(), { keepAlive: 600 })`)
278
+ * and persisting it, or by picking a free one out of
279
+ * {@link Browser.sessions} — an entry with a `connectionId` is already held
280
+ * by another worker.
281
+ *
282
+ * The session is deliberately **left open** afterwards — closing it is the
283
+ * whole thing you are avoiding. Close it when the flow is done by passing
284
+ * `close: true`, or let `keepAlive` lapse.
285
+ *
286
+ * This is what makes agent-style browsing possible: a model calls
287
+ * `navigate`, then `click`, then `extract` as three separate action
288
+ * invocations, and the page has to survive between them. With only the
289
+ * per-call lifecycle each step got a fresh browser, so `click` ran against
290
+ * a blank page — silently, which is the worst shape for that bug.
291
+ */
292
+ connect: <T>(sessionId: string, function_: (browser: BrowserLike) => Promise<T>, options?: {
293
+ close?: boolean;
294
+ }) => Promise<T>;
196
295
  /** Serialized HTML of `url` after navigation settles. */
197
296
  content: (url: string, options?: NavigateOptions) => Promise<string>;
198
297
  /**
199
- * Low-level escape hatch: launch a raw Playwright `Browser` and hand it to
200
- * `fn` (e.g. for multi-page flows or APIs not surfaced here). The browser is
201
- * **always closed** when `fn` resolves or throws — do not retain references
202
- * to it past the callback.
203
- */
204
- launch: <T>(function_: (browser: BrowserLike) => Promise<T>) => Promise<T>;
298
+ * Low-level escape hatch: launch a raw Playwright `Browser` and hand it to
299
+ * `fn` (e.g. for multi-page flows or APIs not surfaced here).
300
+ *
301
+ * The browser is **always closed** when `fn` resolves or throws — unless
302
+ * `keepAlive` is set, which holds the session open for that many seconds so
303
+ * a later {@link Browser.connect} can re-attach. Do not retain references to
304
+ * the browser past the callback either way.
305
+ */
306
+ launch: <T>(function_: (browser: BrowserLike) => Promise<T>, options?: {
307
+ keepAlive?: number;
308
+ }) => Promise<T>;
205
309
  /** Render `url` to a PDF buffer. */
206
310
  pdf: (url: string, options?: PdfOptions) => Promise<Uint8Array>;
207
311
  /**
208
- * Navigate to `url`, run `fn` inside the page context, and return its
209
- * (serializable) result. `fn` runs in the browser, not the worker — it
210
- * cannot close over worker-side variables.
211
- */
312
+ * Navigate to `url`, run `fn` inside the page context, and return its
313
+ * (serializable) result. `fn` runs in the browser, not the worker — it
314
+ * cannot close over worker-side variables.
315
+ */
212
316
  scrape: <T>(url: string, function_: (...args: never[]) => T, options?: NavigateOptions) => Promise<T>;
213
317
  /** Render `url` to an image buffer (PNG by default). */
214
318
  screenshot: (url: string, options?: ScreenshotOptions) => Promise<Uint8Array>;
319
+ /**
320
+ * List the live Browser Rendering sessions for this binding, so a caller can
321
+ * pick a free one to {@link Browser.connect} to. An entry with a
322
+ * `connectionId` is already held by another worker.
323
+ */
324
+ sessions: () => Promise<ReadonlyArray<BrowserSession>>;
215
325
  }
326
+ /**
327
+ * `createBrowser` is part of the experimental `@lunora/browser` API and may change without a major version bump.
328
+ * @experimental
329
+ */
216
330
  declare const createBrowser: (options: LunoraBrowserOptions) => Browser;
217
331
  export { type Browser, type BrowserBindingLike, type BrowserContextLike, type BrowserLaunchLike, type BrowserLike, type LunoraBrowserOptions, type NavigateOptions, type PageLike, type PdfOptions, type ScreenshotOptions, createBrowser };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { createBrowser } from './packem_shared/createBrowser-DW6h6Xuz.mjs';
1
+ import{createBrowser as o}from"./packem_shared/createBrowser-BicVf2xu.mjs";export{o as createBrowser};
@@ -0,0 +1 @@
1
+ import{LunoraError as l}from"@lunora/errors";const O=/^\d{1,3}$/u,x=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,V=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,C=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u,F=/^::([\da-f]{1,4}):([\da-f]{1,4})$/u,q=/^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/u,X=/^\[|\]$/gu,Q=/\.$/u,v=t=>{const e=t.split(".");if(e.length!==4)return;const r=e.map(n=>O.test(n)?Number(n):-1);if(!r.some(n=>n<0||n>255))return[r[0],r[1],r[2],r[3]]},y=([t,e])=>t===0||t===10||t===127||t===100&&e>=64&&e<=127||t===169&&e===254||t===172&&e>=16&&e<=31||t===192&&e===168||t>=224,D=(t,e)=>{const r=Number.parseInt(t??"",16),n=Number.parseInt(e??"",16);return!Number.isFinite(r)||!Number.isFinite(n)?!0:y([Math.floor(r/256),r%256,Math.floor(n/256),n%256])},$=t=>{const e=t.toLowerCase(),r=x.exec(e);if(r)return D(r[1],r[2]);const n=V.exec(e);if(n){const f=v(n[1]??"");return f===void 0||y(f)}const a=C.exec(e);if(a){const f=v(a[1]??"");return f===void 0||y(f)}const c=F.exec(e);return c?D(c[1],c[2]):q.test(e)||e.startsWith("2002:")||e.startsWith("2001:0:")?!0:e==="::"||e==="::1"||e.startsWith("fc")||e.startsWith("fd")||e.startsWith("fe8")||e.startsWith("fe9")||e.startsWith("fea")||e.startsWith("feb")},z=t=>t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal")||t.endsWith(".home.arpa"),h=t=>t.replaceAll(X,"").replace(Q,"").toLowerCase(),L=t=>{const e=h(t);if(e.includes(":"))return $(e);const r=v(e);return r===void 0?z(e):y(r)},G="https://cloudflare-dns.com/dns-query",E=1,R=28,j=2e3,Y=(t,e)=>{if(e===E){const r=v(t);return r===void 0||y(r)}return $(t.toLowerCase())},N=async(t,e,r)=>{try{const n=await fetch(`${G}?name=${encodeURIComponent(t)}&type=${String(e)}`,{headers:{accept:"application/dns-json"},signal:AbortSignal.timeout(r)});return n.ok?(await n.json()).Answer??[]:void 0}catch{return}},K=async(t,e=j)=>{const r=h(t);if(r.includes(":")||v(r)!==void 0)return{kind:"unknown"};const[n,a]=await Promise.all([N(r,E,e),N(r,R,e)]);if(n===void 0&&a===void 0)return{kind:"unknown"};for(const c of[...n??[],...a??[]])if((c.type===E||c.type===R)&&Y(c.data,c.type))return{address:c.data,kind:"private"};return{kind:"public"}},A=3e4,J=12e4,Z=3840,tt=4320,W=5e3,M=async(t,e=W)=>{const r=h(new URL(t).hostname),n=await K(r,e);if(n.kind==="private")throw new l("FORBIDDEN",`@lunora/browser: url host "${r}" resolves to a private/internal address (${n.address}); refusing to navigate (DNS-rebinding guard)`)},H=(t,e,r)=>{if(typeof t!="string"||t.length===0)throw new l("BAD_REQUEST","@lunora/browser: url must be a non-empty string");let n;try{n=new URL(t)}catch{throw new l("BAD_REQUEST",`@lunora/browser: url must be an absolute http(s) URL (got "${t}")`)}if(n.protocol!=="http:"&&n.protocol!=="https:")throw new l("BAD_REQUEST",`@lunora/browser: url protocol must be http(s) (got "${n.protocol}")`);if(n.username!==""||n.password!=="")throw new l("BAD_REQUEST","@lunora/browser: url must not embed credentials (strip the `user:pass@` userinfo)");if(r&&r.length>0){const a=h(n.hostname);if(!r.some(c=>h(c)===a))throw new l("FORBIDDEN",`@lunora/browser: url host "${n.hostname}" is not in the configured allowedHosts allowlist`)}if(!e&&L(n.hostname))throw new l("FORBIDDEN",`@lunora/browser: url host "${n.hostname}" is a private/internal address; pass createBrowser({ …, allowPrivateTargets: true }) to allow it`);return n.toString()},S=(t,e)=>Number.isFinite(t)?Math.min(Math.max(1,Math.floor(t)),e):e,et=t=>({height:S(t.height,tt),width:S(t.width,Z)}),rt=(t,e)=>{const r=t??e??A,n=Number.isFinite(r)?r:A;return Math.min(Math.max(1,Math.floor(n)),J)},nt=async(t,e)=>{let r;try{return await Promise.race([t(),new Promise((n,a)=>{r=setTimeout(()=>{a(new l("BROWSER_TIMEOUT",`@lunora/browser: navigation + operation exceeded the ${String(e)}ms timeout budget`,{status:504}))},e)})])}finally{r!==void 0&&clearTimeout(r)}},B=async t=>{try{await t.close()}catch{}},dt=t=>{if(!t.binding)throw new TypeError("@lunora/browser: `binding` is required (env.BROWSER)");const e=()=>{if(!t.launch)throw new l("INTERNAL",'@lunora/browser: `launch` is not available — install the `@cloudflare/playwright` peer dependency. The generated worker wires it for you; outside codegen pass it via createBrowser({ binding, launch }) (import { launch } from "@cloudflare/playwright").');return t.launch},r=(o,s)=>{if(!o)throw new l("INTERNAL",`@lunora/browser: \`${s}\` is not available — install the \`@cloudflare/playwright\` peer dependency. The generated worker wires it for you; outside codegen pass it via createBrowser({ binding, ${s} }).`);return o},n=async(o,s)=>{const i=await e()(t.binding,s===void 0?void 0:{keep_alive:s*1e3});if(s!==void 0)return await o(i);try{return await o(i)}finally{await B(i)}},a=async(o,s,i,u)=>{const g=t.allowPrivateTargets??!1,I=H(o,g,t.allowedHosts),b=rt(s.timeoutMs,t.timeoutMs),P=t.resolveDns??(t.allowedHosts?.length??0)===0,_=Math.min(b,W);!g&&P&&await M(I,_);const k=async m=>{H(m,g,t.allowedHosts),!g&&P&&await M(m,_)},U=m=>{let p;try{p=new URL(m)}catch{return!1}if(p.protocol!=="http:"&&p.protocol!=="https:")return!1;if(t.allowedHosts&&t.allowedHosts.length>0){const d=h(p.hostname);if(!t.allowedHosts.some(w=>h(w)===d))return!0}return L(p.hostname)};return n(async m=>{const d=await(await m.newContext()).newPage();return d.route&&(!g||(t.allowedHosts?.length??0)>0)&&await d.route("**/*",async w=>{const T=w.request();if(!(T.isNavigationRequest?.()??!0)){if(U(T.url())){await w.abort("blockedbyclient");return}await w.continue();return}try{await k(T.url())}catch{await w.abort("blockedbyclient");return}await w.continue()}),u&&d.setViewportSize&&await d.setViewportSize(et(u)),nt(async()=>(await d.goto(I,{timeout:b,waitUntil:s.waitUntil??"load"}),i(d)),b)})};return{connect:async(o,s,i={})=>{const u=await r(t.connect,"connect")(t.binding,o);if(i.close!==!0)return await s(u);try{return await s(u)}finally{await B(u)}},content:async(o,s={})=>a(o,s,async i=>i.content()),launch:async(o,s={})=>n(o,s.keepAlive),pdf:async(o,s={})=>a(o,s,async i=>i.pdf({format:s.format,printBackground:s.printBackground??!1}),s.viewport),scrape:async(o,s,i={})=>a(o,i,async u=>u.evaluate(s)),screenshot:async(o,s={})=>a(o,s,async i=>i.screenshot({fullPage:s.fullPage??!1,type:s.type??"png"}),s.viewport),sessions:async()=>await r(t.sessions,"sessions")(t.binding)}};export{dt as createBrowser};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/browser",
3
- "version": "1.0.0-alpha.3",
3
+ "version": "1.0.0-alpha.30",
4
4
  "description": "Cloudflare Browser Rendering for Lunora: ctx.browser screenshots, PDF, and scraping in actions",
5
5
  "keywords": [
6
6
  "browser-rendering",
@@ -45,6 +45,9 @@
45
45
  "publishConfig": {
46
46
  "access": "public"
47
47
  },
48
+ "dependencies": {
49
+ "@lunora/errors": "1.0.0-alpha.23"
50
+ },
48
51
  "peerDependencies": {
49
52
  "@cloudflare/playwright": ">=1.0.0"
50
53
  },
@@ -1,268 +0,0 @@
1
- const DEFAULT_TIMEOUT_MS = 3e4;
2
- const MAX_TIMEOUT_MS = 12e4;
3
- const MAX_VIEWPORT_WIDTH = 3840;
4
- const MAX_VIEWPORT_HEIGHT = 4320;
5
- const IPV4_OCTET = /^\d{1,3}$/;
6
- const IPV6_MAPPED_HEX = /^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/;
7
- const IPV6_MAPPED_DOTTED = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/;
8
- const IPV6_COMPATIBLE_DOTTED = /^::(\d{1,3}(?:\.\d{1,3}){3})$/;
9
- const IPV6_COMPATIBLE_HEX = /^::([\da-f]{1,4}):([\da-f]{1,4})$/;
10
- const IPV6_NAT64_HEX = /^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/;
11
- const IPV6_BRACKETS = /^\[|\]$/g;
12
- const TRAILING_DOT = /\.$/;
13
- const parseIpv4 = (host) => {
14
- const parts = host.split(".");
15
- if (parts.length !== 4) {
16
- return void 0;
17
- }
18
- const octets = parts.map((part) => IPV4_OCTET.test(part) ? Number(part) : -1);
19
- if (octets.some((octet) => octet < 0 || octet > 255)) {
20
- return void 0;
21
- }
22
- const result = [octets[0], octets[1], octets[2], octets[3]];
23
- return result;
24
- };
25
- const isPrivateIpv4 = ([a, b]) => a === 0 || // 0.0.0.0/8 "this host"
26
- a === 10 || // 10.0.0.0/8 private
27
- a === 127 || // 127.0.0.0/8 loopback
28
- a === 100 && b >= 64 && b <= 127 || // 100.64.0.0/10 CGNAT
29
- a === 169 && b === 254 || // 169.254.0.0/16 link-local (incl. 169.254.169.254 metadata)
30
- a === 172 && b >= 16 && b <= 31 || // 172.16.0.0/12 private
31
- a === 192 && b === 168 || // 192.168.0.0/16 private
32
- a >= 224;
33
- const isPrivateEmbeddedIpv4 = (highGroup, lowGroup) => {
34
- const high = Number.parseInt(highGroup ?? "", 16);
35
- const low = Number.parseInt(lowGroup ?? "", 16);
36
- if (!Number.isFinite(high) || !Number.isFinite(low)) {
37
- return true;
38
- }
39
- return isPrivateIpv4([Math.floor(high / 256), high % 256, Math.floor(low / 256), low % 256]);
40
- };
41
- const isPrivateIpv6 = (host) => {
42
- const ip = host.toLowerCase();
43
- const mappedHex = IPV6_MAPPED_HEX.exec(ip);
44
- if (mappedHex) {
45
- return isPrivateEmbeddedIpv4(mappedHex[1], mappedHex[2]);
46
- }
47
- const mappedDotted = IPV6_MAPPED_DOTTED.exec(ip);
48
- if (mappedDotted) {
49
- const v4 = parseIpv4(mappedDotted[1] ?? "");
50
- return v4 === void 0 || isPrivateIpv4(v4);
51
- }
52
- const compatDotted = IPV6_COMPATIBLE_DOTTED.exec(ip);
53
- if (compatDotted) {
54
- const v4 = parseIpv4(compatDotted[1] ?? "");
55
- return v4 === void 0 || isPrivateIpv4(v4);
56
- }
57
- const compatHex = IPV6_COMPATIBLE_HEX.exec(ip);
58
- if (compatHex) {
59
- return isPrivateEmbeddedIpv4(compatHex[1], compatHex[2]);
60
- }
61
- if (IPV6_NAT64_HEX.test(ip)) {
62
- return true;
63
- }
64
- return ip === "::" || // unspecified
65
- ip === "::1" || // loopback
66
- ip.startsWith("fc") || // fc00::/7 unique-local
67
- ip.startsWith("fd") || // fc00::/7 unique-local
68
- ip.startsWith("fe8") || // fe80::/10 link-local
69
- ip.startsWith("fe9") || ip.startsWith("fea") || ip.startsWith("feb");
70
- };
71
- const DOH_ENDPOINT = "https://cloudflare-dns.com/dns-query";
72
- const DOH_TIMEOUT_MS = 5e3;
73
- const DNS_TYPE_A = 1;
74
- const DNS_TYPE_AAAA = 28;
75
- const normalizeHost = (host) => host.replaceAll(IPV6_BRACKETS, "").replace(TRAILING_DOT, "").toLowerCase();
76
- const isPrivateResolvedIp = (data, type) => {
77
- if (type === DNS_TYPE_A) {
78
- const v4 = parseIpv4(data);
79
- return v4 === void 0 || isPrivateIpv4(v4);
80
- }
81
- return isPrivateIpv6(data.toLowerCase());
82
- };
83
- const dohLookup = async (hostname, type, timeoutMs = DOH_TIMEOUT_MS) => {
84
- try {
85
- const response = await fetch(`${DOH_ENDPOINT}?name=${encodeURIComponent(hostname)}&type=${String(type)}`, {
86
- headers: { accept: "application/dns-json" },
87
- // Bound the lookup so a stalled resolver can't hang the worker; an
88
- // abort surfaces as a rejection caught below → `undefined` → the
89
- // caller falls back to the (already-passed) string guard.
90
- signal: AbortSignal.timeout(timeoutMs)
91
- });
92
- if (!response.ok) {
93
- return void 0;
94
- }
95
- const body = await response.json();
96
- return body.Answer ?? [];
97
- } catch {
98
- return void 0;
99
- }
100
- };
101
- const assertResolvedHostIsPublic = async (target, timeoutMs = DOH_TIMEOUT_MS) => {
102
- const host = normalizeHost(new URL(target).hostname);
103
- if (host.includes(":") || parseIpv4(host) !== void 0) {
104
- return;
105
- }
106
- const [aRecords, aaaaRecords] = await Promise.all([dohLookup(host, DNS_TYPE_A, timeoutMs), dohLookup(host, DNS_TYPE_AAAA, timeoutMs)]);
107
- if (aRecords === void 0 && aaaaRecords === void 0) {
108
- return;
109
- }
110
- for (const answer of [...aRecords ?? [], ...aaaaRecords ?? []]) {
111
- if ((answer.type === DNS_TYPE_A || answer.type === DNS_TYPE_AAAA) && isPrivateResolvedIp(answer.data, answer.type)) {
112
- throw new Error(
113
- `@lunora/browser: url host "${host}" resolves to a private/internal address (${answer.data}); refusing to navigate (DNS-rebinding guard)`
114
- );
115
- }
116
- }
117
- };
118
- const isPrivateHostname = (host) => host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".home.arpa");
119
- const isPrivateTarget = (parsed) => {
120
- const host = parsed.hostname.replaceAll(IPV6_BRACKETS, "").replace(TRAILING_DOT, "");
121
- if (host.includes(":")) {
122
- return isPrivateIpv6(host);
123
- }
124
- const v4 = parseIpv4(host);
125
- return v4 === void 0 ? isPrivateHostname(host.toLowerCase()) : isPrivateIpv4(v4);
126
- };
127
- const validateUrl = (url, allowPrivateTargets, allowedHosts) => {
128
- if (typeof url !== "string" || url.length === 0) {
129
- throw new Error("@lunora/browser: url must be a non-empty string");
130
- }
131
- let parsed;
132
- try {
133
- parsed = new URL(url);
134
- } catch {
135
- throw new Error(`@lunora/browser: url must be an absolute http(s) URL (got "${url}")`);
136
- }
137
- if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
138
- throw new Error(`@lunora/browser: url protocol must be http(s) (got "${parsed.protocol}")`);
139
- }
140
- if (parsed.username !== "" || parsed.password !== "") {
141
- throw new Error("@lunora/browser: url must not embed credentials (strip the `user:pass@` userinfo)");
142
- }
143
- if (allowedHosts && allowedHosts.length > 0) {
144
- const host = normalizeHost(parsed.hostname);
145
- if (!allowedHosts.some((entry) => normalizeHost(entry) === host)) {
146
- throw new Error(`@lunora/browser: url host "${parsed.hostname}" is not in the configured allowedHosts allowlist`);
147
- }
148
- }
149
- if (!allowPrivateTargets && isPrivateTarget(parsed)) {
150
- throw new Error(
151
- `@lunora/browser: url host "${parsed.hostname}" is a private/internal address; pass createBrowser({ …, allowPrivateTargets: true }) to allow it`
152
- );
153
- }
154
- return parsed.toString();
155
- };
156
- const clampDimension = (value, max) => {
157
- if (!Number.isFinite(value)) {
158
- return max;
159
- }
160
- return Math.min(Math.max(1, Math.floor(value)), max);
161
- };
162
- const clampViewport = (viewport) => {
163
- return {
164
- height: clampDimension(viewport.height, MAX_VIEWPORT_HEIGHT),
165
- width: clampDimension(viewport.width, MAX_VIEWPORT_WIDTH)
166
- };
167
- };
168
- const resolveTimeout = (callTimeout, factoryTimeout) => {
169
- const requested = callTimeout ?? factoryTimeout ?? DEFAULT_TIMEOUT_MS;
170
- const safe = Number.isFinite(requested) ? requested : DEFAULT_TIMEOUT_MS;
171
- return Math.min(Math.max(1, Math.floor(safe)), MAX_TIMEOUT_MS);
172
- };
173
- const createBrowser = (options) => {
174
- if (!options.binding) {
175
- throw new Error("@lunora/browser: `binding` is required (env.BROWSER)");
176
- }
177
- const getLaunch = () => {
178
- if (!options.launch) {
179
- throw new Error(
180
- '@lunora/browser: `launch` is not available — install the `@cloudflare/playwright` peer dependency. The generated worker wires it for you; outside codegen pass it via createBrowser({ binding, launch }) (import { launch } from "@cloudflare/playwright").'
181
- );
182
- }
183
- return options.launch;
184
- };
185
- const withBrowser = async (use) => {
186
- const browser = await getLaunch()(options.binding);
187
- try {
188
- return await use(browser);
189
- } finally {
190
- try {
191
- await browser.close();
192
- } catch {
193
- }
194
- }
195
- };
196
- const withPage = async (url, navigate, use, viewport) => {
197
- const allowPrivateTargets = options.allowPrivateTargets ?? false;
198
- const target = validateUrl(url, allowPrivateTargets, options.allowedHosts);
199
- const timeout = resolveTimeout(navigate.timeoutMs, options.timeoutMs);
200
- const resolveDns = options.resolveDns ?? false;
201
- const dohTimeout = Math.min(timeout, DOH_TIMEOUT_MS);
202
- if (!allowPrivateTargets && resolveDns) {
203
- await assertResolvedHostIsPublic(target, dohTimeout);
204
- }
205
- const assertNavigationAllowed = async (requestUrl) => {
206
- validateUrl(requestUrl, allowPrivateTargets, options.allowedHosts);
207
- if (resolveDns) {
208
- await assertResolvedHostIsPublic(requestUrl, dohTimeout);
209
- }
210
- };
211
- return withBrowser(async (browser) => {
212
- const context = await browser.newContext();
213
- const page = await context.newPage();
214
- if (!allowPrivateTargets && page.route) {
215
- await page.route("**/*", async (route) => {
216
- const request = route.request();
217
- const isNavigation = request.isNavigationRequest?.() ?? true;
218
- if (!isNavigation) {
219
- await route.continue();
220
- return;
221
- }
222
- try {
223
- await assertNavigationAllowed(request.url());
224
- } catch {
225
- await route.abort("blockedbyclient");
226
- return;
227
- }
228
- await route.continue();
229
- });
230
- }
231
- if (viewport && page.setViewportSize) {
232
- await page.setViewportSize(clampViewport(viewport));
233
- }
234
- await page.goto(target, { timeout, waitUntil: navigate.waitUntil ?? "load" });
235
- return use(page);
236
- });
237
- };
238
- const screenshot = async (url, screenshotOptions = {}) => withPage(
239
- url,
240
- screenshotOptions,
241
- async (page) => page.screenshot({
242
- fullPage: screenshotOptions.fullPage ?? false,
243
- type: screenshotOptions.type ?? "png"
244
- }),
245
- screenshotOptions.viewport
246
- );
247
- const pdf = async (url, pdfOptions = {}) => withPage(
248
- url,
249
- pdfOptions,
250
- async (page) => page.pdf({
251
- format: pdfOptions.format,
252
- printBackground: pdfOptions.printBackground ?? false
253
- }),
254
- pdfOptions.viewport
255
- );
256
- const content = async (url, navigateOptions = {}) => withPage(url, navigateOptions, async (page) => page.content());
257
- const scrape = async (url, function_, navigateOptions = {}) => withPage(url, navigateOptions, async (page) => page.evaluate(function_));
258
- const launch = async (function_) => withBrowser(function_);
259
- return {
260
- content,
261
- launch,
262
- pdf,
263
- scrape,
264
- screenshot
265
- };
266
- };
267
-
268
- export { createBrowser };