ant0-browser 0.0.0-stage → 0.2.0-beta.2

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 (163) hide show
  1. package/LICENSE +35 -0
  2. package/README.md +208 -2
  3. package/dist/canvas.d.ts +55 -0
  4. package/dist/canvas.d.ts.map +1 -0
  5. package/dist/canvas.js +82 -0
  6. package/dist/canvas.js.map +1 -0
  7. package/dist/chromium-version.d.ts +22 -0
  8. package/dist/chromium-version.d.ts.map +1 -0
  9. package/dist/chromium-version.js +22 -0
  10. package/dist/chromium-version.js.map +1 -0
  11. package/dist/claim-hints.d.ts +36 -0
  12. package/dist/claim-hints.d.ts.map +1 -0
  13. package/dist/claim-hints.js +9 -0
  14. package/dist/claim-hints.js.map +1 -0
  15. package/dist/cleanup.d.ts +35 -0
  16. package/dist/cleanup.d.ts.map +1 -0
  17. package/dist/cleanup.js +106 -0
  18. package/dist/cleanup.js.map +1 -0
  19. package/dist/content.d.ts +11 -0
  20. package/dist/content.d.ts.map +1 -0
  21. package/dist/content.js +52 -0
  22. package/dist/content.js.map +1 -0
  23. package/dist/download.d.ts +24 -0
  24. package/dist/download.d.ts.map +1 -0
  25. package/dist/download.js +227 -0
  26. package/dist/download.js.map +1 -0
  27. package/dist/errors.d.ts +49 -0
  28. package/dist/errors.d.ts.map +1 -0
  29. package/dist/errors.js +53 -0
  30. package/dist/errors.js.map +1 -0
  31. package/dist/fingerprint.d.ts +218 -0
  32. package/dist/fingerprint.d.ts.map +1 -0
  33. package/dist/fingerprint.js +475 -0
  34. package/dist/fingerprint.js.map +1 -0
  35. package/dist/fontpack.d.ts +13 -0
  36. package/dist/fontpack.d.ts.map +1 -0
  37. package/dist/fontpack.js +150 -0
  38. package/dist/fontpack.js.map +1 -0
  39. package/dist/fonts.d.ts +15 -0
  40. package/dist/fonts.d.ts.map +1 -0
  41. package/dist/fonts.js +86 -0
  42. package/dist/fonts.js.map +1 -0
  43. package/dist/geoip.d.ts +45 -0
  44. package/dist/geoip.d.ts.map +1 -0
  45. package/dist/geoip.js +290 -0
  46. package/dist/geoip.js.map +1 -0
  47. package/dist/geometry.d.ts +32 -0
  48. package/dist/geometry.d.ts.map +1 -0
  49. package/dist/geometry.js +85 -0
  50. package/dist/geometry.js.map +1 -0
  51. package/dist/humanize.d.ts +20 -0
  52. package/dist/humanize.d.ts.map +1 -0
  53. package/dist/humanize.js +921 -0
  54. package/dist/humanize.js.map +1 -0
  55. package/dist/identity-persistence.d.ts +88 -0
  56. package/dist/identity-persistence.d.ts.map +1 -0
  57. package/dist/identity-persistence.js +381 -0
  58. package/dist/identity-persistence.js.map +1 -0
  59. package/dist/identity.d.ts +81 -0
  60. package/dist/identity.d.ts.map +1 -0
  61. package/dist/identity.js +370 -0
  62. package/dist/identity.js.map +1 -0
  63. package/dist/index.d.ts +281 -0
  64. package/dist/index.d.ts.map +1 -0
  65. package/dist/index.js +790 -0
  66. package/dist/index.js.map +1 -0
  67. package/dist/launch-ticket.d.ts +191 -0
  68. package/dist/launch-ticket.d.ts.map +1 -0
  69. package/dist/launch-ticket.js +549 -0
  70. package/dist/launch-ticket.js.map +1 -0
  71. package/dist/launchopts.d.ts +266 -0
  72. package/dist/launchopts.d.ts.map +1 -0
  73. package/dist/launchopts.js +623 -0
  74. package/dist/launchopts.js.map +1 -0
  75. package/dist/motion.d.ts +106 -0
  76. package/dist/motion.d.ts.map +1 -0
  77. package/dist/motion.js +311 -0
  78. package/dist/motion.js.map +1 -0
  79. package/dist/motionscore.d.ts +57 -0
  80. package/dist/motionscore.d.ts.map +1 -0
  81. package/dist/motionscore.js +215 -0
  82. package/dist/motionscore.js.map +1 -0
  83. package/dist/native/linux-x64/PRODUCT-LICENSE.txt +28 -0
  84. package/dist/native/linux-x64/ant0_runtime.node +0 -0
  85. package/dist/native/windows-x64/PRODUCT-LICENSE.txt +28 -0
  86. package/dist/native/windows-x64/ant0_runtime.node +0 -0
  87. package/dist/persona-migration.d.ts +54 -0
  88. package/dist/persona-migration.d.ts.map +1 -0
  89. package/dist/persona-migration.js +97 -0
  90. package/dist/persona-migration.js.map +1 -0
  91. package/dist/persona-profile-v2.d.ts +169 -0
  92. package/dist/persona-profile-v2.d.ts.map +1 -0
  93. package/dist/persona-profile-v2.js +454 -0
  94. package/dist/persona-profile-v2.js.map +1 -0
  95. package/dist/persona-profile-v4.d.ts +61 -0
  96. package/dist/persona-profile-v4.d.ts.map +1 -0
  97. package/dist/persona-profile-v4.js +79 -0
  98. package/dist/persona-profile-v4.js.map +1 -0
  99. package/dist/persona-rejected.d.ts +36 -0
  100. package/dist/persona-rejected.d.ts.map +1 -0
  101. package/dist/persona-rejected.js +40 -0
  102. package/dist/persona-rejected.js.map +1 -0
  103. package/dist/population-model.d.ts +45 -0
  104. package/dist/population-model.d.ts.map +1 -0
  105. package/dist/population-model.js +245 -0
  106. package/dist/population-model.js.map +1 -0
  107. package/dist/profile-file.d.ts +201 -0
  108. package/dist/profile-file.d.ts.map +1 -0
  109. package/dist/profile-file.js +736 -0
  110. package/dist/profile-file.js.map +1 -0
  111. package/dist/release-fetch.d.ts +74 -0
  112. package/dist/release-fetch.d.ts.map +1 -0
  113. package/dist/release-fetch.js +395 -0
  114. package/dist/release-fetch.js.map +1 -0
  115. package/dist/release.d.ts +16 -0
  116. package/dist/release.d.ts.map +1 -0
  117. package/dist/release.js +26 -0
  118. package/dist/release.js.map +1 -0
  119. package/dist/render.d.ts +38 -0
  120. package/dist/render.d.ts.map +1 -0
  121. package/dist/render.js +104 -0
  122. package/dist/render.js.map +1 -0
  123. package/dist/runtime-client.d.ts +47 -0
  124. package/dist/runtime-client.d.ts.map +1 -0
  125. package/dist/runtime-client.js +327 -0
  126. package/dist/runtime-client.js.map +1 -0
  127. package/dist/runtime-launch.d.ts +22 -0
  128. package/dist/runtime-launch.d.ts.map +1 -0
  129. package/dist/runtime-launch.js +92 -0
  130. package/dist/runtime-launch.js.map +1 -0
  131. package/dist/scale.d.ts +29 -0
  132. package/dist/scale.d.ts.map +1 -0
  133. package/dist/scale.js +105 -0
  134. package/dist/scale.js.map +1 -0
  135. package/dist/shaderdialect.d.ts +33 -0
  136. package/dist/shaderdialect.d.ts.map +1 -0
  137. package/dist/shaderdialect.js +47 -0
  138. package/dist/shaderdialect.js.map +1 -0
  139. package/dist/speech-coherence.d.ts +52 -0
  140. package/dist/speech-coherence.d.ts.map +1 -0
  141. package/dist/speech-coherence.js +254 -0
  142. package/dist/speech-coherence.js.map +1 -0
  143. package/dist/template-selection.d.ts +14 -0
  144. package/dist/template-selection.d.ts.map +1 -0
  145. package/dist/template-selection.js +66 -0
  146. package/dist/template-selection.js.map +1 -0
  147. package/dist/warnings.d.ts +50 -0
  148. package/dist/warnings.d.ts.map +1 -0
  149. package/dist/warnings.js +273 -0
  150. package/dist/warnings.js.map +1 -0
  151. package/dist/webgl-coherence.d.ts +30 -0
  152. package/dist/webgl-coherence.d.ts.map +1 -0
  153. package/dist/webgl-coherence.js +98 -0
  154. package/dist/webgl-coherence.js.map +1 -0
  155. package/dist/webgpu-override.d.ts +14 -0
  156. package/dist/webgpu-override.d.ts.map +1 -0
  157. package/dist/webgpu-override.js +82 -0
  158. package/dist/webgpu-override.js.map +1 -0
  159. package/dist/widevine.d.ts +44 -0
  160. package/dist/widevine.d.ts.map +1 -0
  161. package/dist/widevine.js +203 -0
  162. package/dist/widevine.js.map +1 -0
  163. package/package.json +56 -4
package/dist/index.js ADDED
@@ -0,0 +1,790 @@
1
+ // Ant0 Browser — Playwright drop-in.
2
+ //
3
+ // import { launch } from "ant0-browser";
4
+ // const browser = await launch({ identity: { mode: "native" } });
5
+ // const page = await browser.newPage();
6
+ // await page.goto("https://abrahamjuliot.github.io/creepjs/");
7
+ //
8
+ // launch() returns a standard Playwright `Browser`, backed by a caller-provided local binary.
9
+ // Every Playwright launch option (headless, proxy, args, timeout, ...) passes through. Identity is
10
+ // selected with the strict native, captured, or synthetic API.
11
+ import { chromium } from "playwright-core";
12
+ import { mkdtempSync, rmSync } from "node:fs";
13
+ import { spawn } from "node:child_process";
14
+ import { createServer } from "node:net";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ import { fingerprintArgs, personaAvail, personaDpr, splitFingerprintOptions } from "./fingerprint.js";
18
+ import { scaleWindowArgs, withDeviceScale } from "./scale.js";
19
+ import { prepareIdentityOptions } from "./identity.js";
20
+ import { installHumanize, installHumanizeOnContext } from "./humanize.js";
21
+ import { FIRST_RUN_HYGIENE_ARGS, defaultStartUrlArgs, extensionArgs, resolveProxy, mergeFeatureFlags, privacySandboxArgs, domStorageBackendArgs, proxyBypassArgs, quicArgs, socks5UdpArgs, webBluetoothArgs, personaPlatformOf, withPlaywrightFeatureDefaults, mergeIgnoreDefaultArgs, gateWebrtcArgs, webrtcDefaultDenyArgs, assertNoReservedArgs, } from "./launchopts.js";
22
+ import { RELEASE, platformRelease } from "./release.js";
23
+ import { fetchWidevine, seedWidevine, widevineArgs } from "./widevine.js";
24
+ import { emitCoherenceWarnings, gpuHostMissingFor } from "./warnings.js";
25
+ import { removeOwnDir, stopChild, track, untrack } from "./cleanup.js";
26
+ import { installedEngineVersion as readInstalledEngineVersion } from "./launch-ticket.js";
27
+ import { fontLaunchEnv } from "./fonts.js";
28
+ import { resolveFontPack } from "./fontpack.js";
29
+ export { resolveFontPack, packFamilies, PACK_VERSION as FONT_PACK_VERSION } from "./fontpack.js";
30
+ import { withShaderDialect } from "./shaderdialect.js";
31
+ import { PersonaFileRejectedError, personaFileRejection } from "./persona-rejected.js";
32
+ import { LaunchTicketRejectedError, hasLaunchTicketArg, rethrowIfTicketRejected, launchTicketRejection, LAUNCH_TICKET_EXIT_CODE, redactError, redactLaunchSecrets, launchSecretValues, applyTicketEnv, argsForTicketDecision, callerEnvTicket, launchTicketArgValue, sdkFetchedTicket, withTicketRetry, dropPartialFirstLine, } from "./launch-ticket.js";
33
+ import { applyHeadlessGeometry, initialWindowArgs, } from "./geometry.js";
34
+ import { manualBinary, withRuntimeLaunch } from "./runtime-launch.js";
35
+ import { assertPersonaFitsEngine, removeStalePersonaFile, stagePersonaProfile } from "./profile-file.js";
36
+ import { emitPersonaNotices } from "./warnings.js";
37
+ import { SdkError, SdkTypeError } from "./errors.js";
38
+ export { RuntimeError } from "./runtime-client.js";
39
+ export { SdkError, SdkInputError, SdkTypeError, SdkRangeError, reportFields } from "./errors.js";
40
+ export { checkInstall, verifyInstall } from "./download.js";
41
+ export { resolveGeo } from "./geoip.js";
42
+ // For callers that attach to an already-running browser (connectOverCDP) rather than launching
43
+ // one: humanize its existing context (current and future pages). Seed it from the identity's
44
+ // fingerprint so the motor persona matches the one a launch would have used.
45
+ export { installHumanizeOnContext } from "./humanize.js";
46
+ // The pure motor model behind humanized input (no page or browser access): seeded personas,
47
+ // mouse trajectories, click points and key/click timings. For callers that drive input over raw
48
+ // CDP themselves and want the same timing model as `humanize: true`.
49
+ export { mulberry32, hashSeed, gaussFrom, makePersona, clickHold, keyDwell, minJerk, planMove, dragDwell, clickPoint, planAmbient, } from "./motion.js";
50
+ export { RELEASE, RELEASE_PUBLIC_KEY } from "./release.js";
51
+ export { installRelease, installedRelease, verifyMinisign, ReleaseError, SignatureError } from "./release-fetch.js";
52
+ export { fetchWidevine, seedWidevine } from "./widevine.js";
53
+ export { checkRenderCoherence } from "./render.js";
54
+ export { setContent } from "./content.js";
55
+ export { PersonaFileRejectedError, personaFileRejection, PERSONA_FILE_EXIT_CODE, PERSONA_FILE_REJECTED_CODE } from "./persona-rejected.js";
56
+ export { LaunchTicketRejectedError, LaunchTicketUnavailableError, launchTicketRejection, fetchLaunchTicket, discoverDaemon, resolveDaemonHome, inferEngineVersion, installedEngineVersion, resolveLaunchTicketArgs, hasLaunchTicketArg, LAUNCH_TICKET_SWITCH, LAUNCH_TICKET_ENV, LAUNCH_TICKET_EXIT_CODE, LAUNCH_TICKET_REJECTED_CODE, ENGINE_VERSION_ENV, } from "./launch-ticket.js";
57
+ export { assertPersonaProfileV2, parsePersonaProfileV2, validatePersonaProfileV2, InvalidPersonaProfileV2Error, WEBGL_PARAMETER_NAMES, WEBGPU_LIMIT_NAMES, } from "./persona-profile-v2.js";
58
+ export { CHROMIUM_VERSION, CHROMIUM_MAJOR, CHROMIUM_UA_VERSION } from "./chromium-version.js";
59
+ export { migratePersonaBrowserMajor, needsMigration, personaBrowserMajor, PersonaMigrationError, MIGRATED_FIELDS, } from "./persona-migration.js";
60
+ export { selectPersonaTemplate, } from "./template-selection.js";
61
+ export { GENERATE_ALGORITHM, GENERATION_ORDER, PopulationModelError, loadPopulationModel, generatePersonaProfile, } from "./population-model.js";
62
+ export { IDENTITY_WRAPPER_VERSION, GENERATED_IDENTITY_WRAPPER_VERSION, TEMPLATE_SELECTION_ALGORITHM, GENERATE_ALGORITHM as GENERATE_IDENTITY_ALGORITHM, IdentityPersistenceError, resolveIdentityDirectory, identityFilename, loadOrCreateDeviceKey, validatePersistedIdentity, loadPersistedIdentity, createOrLoadIdentity, createOrLoadGeneratedIdentity, createOrLoadIssuedIdentity, ISSUED_IDENTITY_WRAPPER_VERSION, } from "./identity-persistence.js";
63
+ export { CANVAS_NOISE_KEY_SWITCH, CANVAS_NOISE_KEY_LENGTH, CANVAS_NOISE_KEY_DOMAIN, canvasMode, isCanvasNoiseKey, newCanvasNoiseKey, deriveCanvasNoiseKey, canvasNoiseKeyFor, } from "./canvas.js";
64
+ export { canvasNoiseKeyOfIdentity } from "./identity.js";
65
+ export { assertPersonaProfileV4, isPersonaV4, PersonaV4SchemaError } from "./persona-profile-v4.js";
66
+ export { PROFILE_FILE_SWITCH, SDK_INFO_SWITCH, PROFILE_FILE_NAME, enginePersonaInfo, enginePersonaSchemas, parseSdkInfoSchemas, writePersonaProfileFile, } from "./profile-file.js";
67
+ export { loadTemplateDirectory, loadCapturedProfile, resolveIdentity, prepareIdentityOptions, } from "./identity.js";
68
+ /** Resolve the real Windows font pack for a launch (Linux + persona only), else undefined. */
69
+ async function fontPackForLaunch(identityMode, resolveFonts, quiet) {
70
+ if (resolveFonts === false || process.platform !== "linux")
71
+ return undefined;
72
+ if (identityMode !== "captured" && identityMode !== "synthetic")
73
+ return undefined;
74
+ return resolveFontPack({ quiet });
75
+ }
76
+ function ensureRunnableHere(exe) {
77
+ if (platformRelease() === undefined) {
78
+ throw new SdkError("sdk.environment_unsupported", `Ant0 Browser ${RELEASE.version} ships Windows x64 and Linux x64 binaries — there is no build for '${process.platform}'.\n` +
79
+ `Run on Windows or Linux, or pass executablePath to a compatible binary.\n` +
80
+ `(The resolved local binary is: ${exe})`);
81
+ }
82
+ }
83
+ /** Resolve the installed default without fetching a ticket. The returned path is informational;
84
+ * launch/serve resolve again and retain native proof through their immediate spawn. */
85
+ export async function executablePath(options = {}) {
86
+ return withRuntimeLaunch({ ...options, launchTicket: false }, r => r.executable);
87
+ }
88
+ /** Headless context defaults ride on newPage/newContext because `chromium.launch()` takes none. */
89
+ function installHeadlessGeometry(browser, geom, dpr) {
90
+ const defaults = geom.mode === "native"
91
+ ? { viewport: null }
92
+ : { screen: geom.screen, viewport: geom.viewport };
93
+ const merge = (o = {}) => withDeviceScale("viewport" in o || "screen" in o ? o : { ...o, ...defaults }, dpr);
94
+ const origNewPage = browser.newPage.bind(browser);
95
+ const origNewContext = browser.newContext.bind(browser);
96
+ browser.newPage =
97
+ async (o = {}) => origNewPage(merge(o));
98
+ browser.newContext =
99
+ async (o = {}) => origNewContext(merge(o));
100
+ }
101
+ /** A headed launch with Playwright's default emulated viewport (1280x720) on the real OS window
102
+ * makes window.innerWidth/Height disagree with the actual window — an impossible-window tell. For a
103
+ * headed browser, default new pages/contexts to `viewport: null` (innerWidth tracks the real window)
104
+ * unless the caller asked for a viewport. */
105
+ function installHeadedViewport(browser, dpr) {
106
+ const merge = (o) => withDeviceScale("viewport" in o || "screen" in o ? o : { ...o, viewport: null }, dpr);
107
+ const origNewPage = browser.newPage.bind(browser);
108
+ browser.newPage = (o = {}) => origNewPage(merge(o));
109
+ const origNewContext = browser.newContext.bind(browser);
110
+ browser.newContext = (o = {}) => origNewContext(merge(o));
111
+ }
112
+ /** The engine release is only known once the executable is resolved, so the `--webrtc-ip` gate
113
+ * (engines older than ant0.3 turn non-proxied UDP back on with it) is applied by each caller to
114
+ * the assembled list, with the version `withRuntimeLaunch` reports. */
115
+ function personaPlatformFor(fp) {
116
+ return personaPlatformOf(fp.platform, fp.fingerprintProfile);
117
+ }
118
+ /** Assemble the final engine args from all layers: identity + extensions + proxy, the
119
+ * Privacy-Sandbox-disable default, the WebRTC leak-proof default, and the user's own args — then
120
+ * collapse all --enable-features/--disable-features into one each (Chromium keeps only the last). */
121
+ function assembleArgs(fpArgs, extArgs, proxyArgs, disablePrivacySandbox, webrtcIp, userArgs, proxyForQuic, socks5Udp, personaPlatform, pinDomStorage = false) {
122
+ assertNoReservedArgs(userArgs);
123
+ // webBluetoothArgs: a Linux host hides navigator.bluetooth while exposing usb/serial/hid, an
124
+ // OS-origin tell on a Windows or macOS persona. Emitted only for such a persona; a Linux persona
125
+ // or a no-persona launch must not have it (real Linux Chrome lacks it).
126
+ const base = [...fpArgs, ...extArgs, ...proxyArgs, ...quicArgs(proxyForQuic), ...socks5UdpArgs(socks5Udp, proxyForQuic), ...webBluetoothArgs(personaPlatform ?? null)];
127
+ // DEFAULT FLIPPED IN 0.23.0 — opt IN to disabling, rather than opt out.
128
+ //
129
+ // Keep these APIs enabled unless the caller explicitly requests the de-Googled policy.
130
+ if (disablePrivacySandbox === true)
131
+ base.push(...privacySandboxArgs());
132
+ // Sync captures only the leveldb DOM storage backend. Direct spawns (serve/launchPlan) pin here;
133
+ // the Playwright launch paths pin inside withPlaywrightFeatureDefaults, only when Playwright's own
134
+ // disabled list is known (else this --disable-features would replace the whole list).
135
+ if (pinDomStorage)
136
+ base.push(...domStorageBackendArgs());
137
+ base.push(...webrtcDefaultDenyArgs([...base, ...userArgs], webrtcIp));
138
+ return mergeFeatureFlags([...base, ...userArgs]);
139
+ }
140
+ /** `widevine: true`: seed the CDM into the profile and fix the launch args so the engine registers it
141
+ * (un-suppress the component updater, force the startup scan on Windows). Best-effort: a failure
142
+ * leaves DRM off and the launch proceeds. Returns the adjusted `ignoreDefaultArgs` and args. */
143
+ async function applyWidevineLaunch(userDataDir, ignoreDefaultArgs, userArgs, quiet) {
144
+ try {
145
+ await seedWidevine(userDataDir, { quiet });
146
+ // The --component-updater=fast-update scan is Windows-only (on Linux the hint file registers
147
+ // the CDM). Only warn about a user-supplied non-fast-update mode where fast-update matters.
148
+ const cu = userArgs.filter((a) => a.includes("component-updater"));
149
+ if (process.platform !== "linux" && cu.length && !cu.some((a) => a.includes("fast-update")) && !quiet) {
150
+ process.stderr.write("[ant0-browser] [widevine] note: your --component-updater mode may not register the CDM; --component-updater=fast-update is needed to scan the pre-installed component\n");
151
+ }
152
+ const tweak = widevineArgs(ignoreDefaultArgs, userArgs);
153
+ return { ignoreDefaultArgs: tweak.ignoreDefaultArgs, args: tweak.args };
154
+ }
155
+ catch (e) {
156
+ if (!quiet)
157
+ process.stderr.write(`[ant0-browser] [widevine] setup failed (continuing without DRM): ${String(e)}\n`);
158
+ return { ignoreDefaultArgs, args: userArgs };
159
+ }
160
+ }
161
+ function applyIdentityOption(options) {
162
+ const prepared = prepareIdentityOptions(options);
163
+ return { options: prepared.options, identityMode: prepared.identityMode };
164
+ }
165
+ /**
166
+ * Delete a throwaway profile directory once its context closes.
167
+ *
168
+ * THE RETRY IS NOT DEFENSIVE PADDING — a single attempt measurably does not work. On Windows the
169
+ * browser still holds handles under the profile directory for a short window after `close()`
170
+ * resolves, so the first removal throws EBUSY/EPERM. Measured on the first build of this change
171
+ * (Python port): the directory survived a close plus a 1.5s wait and leaked silently.
172
+ *
173
+ * Two triggers, because neither alone is enough: `close` covers an orderly shutdown, and the
174
+ * process-exit hook covers a script that throws or is interrupted with the browser still open.
175
+ * Both funnel through one idempotent remove.
176
+ */
177
+ function installEphemeralProfileCleanup(context, userDataDir) {
178
+ let done = false;
179
+ const remove = async () => {
180
+ if (done)
181
+ return;
182
+ for (let attempt = 0; attempt < 6; attempt++) {
183
+ try {
184
+ rmSync(userDataDir, { recursive: true, force: true });
185
+ done = true;
186
+ return;
187
+ }
188
+ catch {
189
+ await new Promise((r) => setTimeout(r, 250 * (attempt + 1))); // 0.25→1.5s, ~5s total
190
+ }
191
+ }
192
+ };
193
+ // Synchronous: an exit handler cannot await, and an unresolved promise at exit removes nothing.
194
+ const onExit = () => {
195
+ if (done)
196
+ return;
197
+ try {
198
+ rmSync(userDataDir, { recursive: true, force: true });
199
+ }
200
+ catch { /* temp sweeper gets it */ }
201
+ };
202
+ process.once("exit", onExit);
203
+ context.on("close", () => {
204
+ void remove().finally(() => {
205
+ if (done)
206
+ process.removeListener("exit", onExit);
207
+ });
208
+ });
209
+ }
210
+ /**
211
+ * Make a persistent BrowserContext satisfy code written against launch()'s Browser.
212
+ *
213
+ * `newContext()` returns THE PERSISTENT CONTEXT ITSELF rather than a fresh incognito one. That is
214
+ * deliberate: a real incognito context would silently leave the profile behind — taking the
215
+ * Widevine CDM and the component-updated state with it — handing back exactly the browser this
216
+ * change exists to stop producing. Two calls returning the same context is a visible, documented
217
+ * compromise; quietly returning a profile-less browser is not.
218
+ */
219
+ function asBrowserLike(context) {
220
+ const c = context;
221
+ if (c.newContext === undefined)
222
+ c.newContext = async () => context;
223
+ if (c.contexts === undefined)
224
+ c.contexts = () => [context];
225
+ return context;
226
+ }
227
+ /**
228
+ * Launch Ant0 Browser and return a Playwright browser handle backed by a REAL Chrome profile.
229
+ *
230
+ * PROFILE-BACKED BY DEFAULT (changed in 0.23.0). This used to be `chromium.launch()` — incognito,
231
+ * no profile directory. Incognito cannot load a component-updated CDM, so
232
+ * `requestMediaKeySystemAccess('com.widevine.alpha')` rejected and the EME surface was a
233
+ * no-Widevine tell on a build branded Google Chrome (measured against the live audit on 150-r10).
234
+ * It now launches a persistent context on a throwaway directory, so `widevine: true` works here.
235
+ *
236
+ * The directory is deleted when the context closes AND on process exit, so nothing is left behind
237
+ * and no state survives to the next launch — the incognito-like isolation callers relied on is
238
+ * preserved. Pass `userDataDir` to keep a profile, or `ephemeralProfile: false` to opt back out.
239
+ */
240
+ export async function launch(options = {}) {
241
+ // ephemeralProfile: false restores the pre-0.23 incognito launch. Kept because the persistent
242
+ // path costs a directory create+delete per launch, which a caller spawning hundreds of
243
+ // short-lived browsers may reasonably not want to pay for a CDM they never touch.
244
+ const { ephemeralProfile, userDataDir, ...restOpts } = options;
245
+ if (userDataDir !== undefined) {
246
+ return asBrowserLike(await launchPersistentContext(userDataDir, restOpts));
247
+ }
248
+ if (ephemeralProfile !== false) {
249
+ const dir = mkdtempSync(join(tmpdir(), "ant0-browser-run-"));
250
+ let context;
251
+ try {
252
+ context = await launchPersistentContext(dir, restOpts);
253
+ }
254
+ catch (error) {
255
+ try {
256
+ rmSync(dir, { recursive: true, force: true });
257
+ }
258
+ catch { /* preserve launch error */ }
259
+ throw error;
260
+ }
261
+ installEphemeralProfileCleanup(context, dir);
262
+ return asBrowserLike(context);
263
+ }
264
+ return launchIncognito(restOpts);
265
+ }
266
+ /** The engine release to judge advisory warnings by: the trusted release record, else (for a
267
+ * development build) its `-ant0.dev` label. Never used for a gate. */
268
+ function advisoryEngineVersion(resolved, exe) {
269
+ return resolved ?? readInstalledEngineVersion(exe, true);
270
+ }
271
+ /** The pre-0.23 incognito launch, reached via `ephemeralProfile: false`. */
272
+ async function launchIncognito(options = {}) {
273
+ return withTicketRetry((note) => launchIncognitoOnce({ ...options }, note));
274
+ }
275
+ async function launchIncognitoOnce(options, note) {
276
+ const identity = applyIdentityOption(options);
277
+ options = identity.options;
278
+ const { extensions, shaderDialect, socks5Udp, disablePrivacySandbox, executablePath: exeOption, args, humanize, showCursor, cacheDir, quiet, resolveFonts, launchTicket, engineVersion, runtime, ...rest } = options;
279
+ const { fingerprint, rest: pwOptions } = splitFingerprintOptions(rest);
280
+ const proxyOpt = pwOptions.proxy; // captured before resolveProxy runs
281
+ // resolveProxy throws for a credentialed SOCKS proxy (nothing in the stack can authenticate to
282
+ // one; use a relay). Every other shape is left to Playwright unchanged.
283
+ const { args: proxyArgs, proxy } = resolveProxy(pwOptions.proxy);
284
+ if (proxy === undefined)
285
+ delete pwOptions.proxy;
286
+ else
287
+ pwOptions.proxy = proxy;
288
+ // Refused before the engine is resolved, probed or any persona file is written.
289
+ assertNoReservedArgs(args ?? []);
290
+ return withRuntimeLaunch({ executablePath: exeOption, runtime, launchTicket, engineVersion, args: argsForTicketDecision(args, pwOptions.env), quiet }, async ({ executable: exe, ticketArgs, engineVersion: resolvedEngine }) => {
291
+ note(sdkFetchedTicket(launchTicket, ticketArgs));
292
+ ensureRunnableHere(exe);
293
+ // Emitted here, not before the engine is resolved: the GPU/canvas gap warnings depend on the engine release.
294
+ emitCoherenceWarnings({ ...fingerprint, proxy: proxyOpt, geoip: false, headless: pwOptions.headless, _userArgs: args ?? [], _cacheDirGiven: cacheDir !== undefined,
295
+ _gpuHostMissing: gpuHostMissingFor(fingerprint, identity.identityMode) }, quiet, process.platform, String(RELEASE.version).split(".")[0], advisoryEngineVersion(resolvedEngine, exe));
296
+ const headed = pwOptions.headless === false;
297
+ // On Linux, point FONTCONFIG_FILE at the bundled metric-compatible clones (Segoe UI, Arial, …).
298
+ const packDir = await fontPackForLaunch(identity.identityMode, resolveFonts, Boolean(quiet));
299
+ const launchEnv = withShaderDialect(shaderDialect, fontLaunchEnv(exe, pwOptions.env, packDir));
300
+ const dpr = personaDpr(fingerprint);
301
+ // Schema 4 personas travel in a private file (no profile dir here, so a temp dir, removed when the browser closes).
302
+ const staged = await stagePersonaProfile(fingerprint, exe);
303
+ emitPersonaNotices(staged.notices, quiet);
304
+ let launched = false;
305
+ try {
306
+ const sdkArgs = scaleWindowArgs(fingerprintArgs(staged.fingerprint, true), dpr, headed, personaAvail(fingerprint), args ?? []);
307
+ let engineArgs = gateWebrtcArgs(assembleArgs(sdkArgs, extensionArgs(extensions), proxyArgs, disablePrivacySandbox, fingerprint.webrtcIp, args ?? [], proxyOpt, socks5Udp, personaPlatformFor(fingerprint)), resolvedEngine, quiet, Boolean(proxyOpt?.server));
308
+ // Headless: screen.* has to be handled alongside the viewport or the window reports a geometry no
309
+ // real browser can (see ./geometry.ts). Probe a copy — viewport/screen are context options, which
310
+ // chromium.launch() does not take — and carry the result to newPage/newContext.
311
+ const geom = headed
312
+ ? null
313
+ : identity.identityMode === "native"
314
+ ? { mode: "native" }
315
+ : applyHeadlessGeometry({ ...pwOptions }, fingerprint.fingerprint, engineArgs);
316
+ engineArgs = initialWindowArgs(engineArgs, geom);
317
+ // Engine patch 0037: the caller's ticket, or one from the local daemon (see ./launch-ticket.ts).
318
+ engineArgs = [...engineArgs, ...ticketArgs];
319
+ // Engine patch 949: the same ticket in ANT0_LAUNCH of the engine child (a copy of the env; never process.env).
320
+ const ticketed = applyTicketEnv(engineArgs, launchEnv, pwOptions.env);
321
+ engineArgs = withPlaywrightFeatureDefaults(ticketed.args, mergeIgnoreDefaultArgs(pwOptions.ignoreDefaultArgs, args), quiet);
322
+ const childEnv = ticketed.env;
323
+ let browser;
324
+ try {
325
+ browser = await chromium.launch({
326
+ // Drop Playwright's default --enable-automation so the engine's AutomationControlled feature
327
+ // stays off (it flips webdriver-adjacent tells). Caller can override via ignoreDefaultArgs.
328
+ ...pwOptions,
329
+ ignoreDefaultArgs: mergeIgnoreDefaultArgs(pwOptions.ignoreDefaultArgs, args),
330
+ executablePath: exe,
331
+ ...(childEnv ? { env: childEnv } : {}),
332
+ args: engineArgs,
333
+ });
334
+ }
335
+ catch (error) {
336
+ rethrowIfTicketRejected(error, launchSecretValues(engineArgs, [], childEnv)); // exit 90 / 91 + stderr line -> LaunchTicketRejectedError / PersonaFileRejectedError
337
+ }
338
+ if (headed) {
339
+ installHeadedViewport(browser, dpr); // launch() takes no viewport option -> wrap newPage/newContext
340
+ }
341
+ else if (geom)
342
+ installHeadlessGeometry(browser, geom, dpr);
343
+ installHumanize(browser, { humanize, showCursor, seed: fingerprint.fingerprint }); // seed => stable motor persona
344
+ staged.removeFile(); // the engine read it at startup: the file does not stay until the browser closes
345
+ browser.once("disconnected", () => staged.cleanup()); // the temp dir goes when the browser does (process exit is the fallback)
346
+ launched = true;
347
+ return browser;
348
+ }
349
+ finally {
350
+ if (!launched)
351
+ staged.cleanup();
352
+ }
353
+ });
354
+ }
355
+ /**
356
+ * Launch Ant0 Browser with a persistent profile directory and return a Playwright
357
+ * {@link BrowserContext} (cookies, storage, etc. persist in `userDataDir`).
358
+ */
359
+ export async function launchPersistentContext(userDataDir, options = {}) {
360
+ return withTicketRetry((note) => launchPersistentContextOnce(userDataDir, { ...options }, note));
361
+ }
362
+ async function launchPersistentContextOnce(userDataDir, options, note) {
363
+ const identity = applyIdentityOption(options);
364
+ options = identity.options;
365
+ const { extensions, shaderDialect, socks5Udp, disablePrivacySandbox, executablePath: exeOption, args, humanize, showCursor, cacheDir, quiet, widevine, resolveFonts, launchTicket, engineVersion, runtime, ...rest } = options;
366
+ const { fingerprint, rest: pwOptions } = splitFingerprintOptions(rest);
367
+ const proxyOpt = pwOptions.proxy; // captured before resolveProxy runs
368
+ // Throws for a credentialed SOCKS proxy (see resolveProxy); other shapes pass through unchanged.
369
+ const { args: proxyArgs, proxy } = resolveProxy(pwOptions.proxy);
370
+ if (proxy === undefined)
371
+ delete pwOptions.proxy;
372
+ else
373
+ pwOptions.proxy = proxy;
374
+ const opts = pwOptions;
375
+ // headed + no explicit viewport -> disable the emulated viewport (impossible-window tell)
376
+ const headedNoViewport = opts.headless === false
377
+ && opts.viewport === undefined && opts.screen === undefined;
378
+ if (headedNoViewport)
379
+ opts.viewport = null;
380
+ // widevine=true: seed the CDM into the profile + un-suppress the component updater (Playwright
381
+ // disables it by default) so the engine registers it. Failure -> DRM gracefully off, launch proceeds.
382
+ // Default the automation strip BEFORE the Widevine helper so it appends --disable-component-update
383
+ // to ['--enable-automation'] rather than clobbering it (losing the strip). Caller's own wins.
384
+ let ignoreDefaultArgs = mergeIgnoreDefaultArgs(opts.ignoreDefaultArgs, args);
385
+ assertNoReservedArgs(args ?? []); // before the profile directory is touched, the engine probed or a persona written
386
+ let userArgs = args ?? [];
387
+ if (widevine) {
388
+ const wv = await applyWidevineLaunch(userDataDir, ignoreDefaultArgs, userArgs, quiet);
389
+ ignoreDefaultArgs = wv.ignoreDefaultArgs;
390
+ userArgs = wv.args;
391
+ }
392
+ delete opts.ignoreDefaultArgs; // passed explicitly below
393
+ return withRuntimeLaunch({ executablePath: exeOption, runtime, launchTicket, engineVersion, args: argsForTicketDecision(userArgs, opts.env), quiet }, async ({ executable: exe, ticketArgs, engineVersion: resolvedEngine }) => {
394
+ note(sdkFetchedTicket(launchTicket, ticketArgs));
395
+ ensureRunnableHere(exe);
396
+ // Emitted here, not before the engine is resolved: the GPU/canvas gap warnings depend on the engine release.
397
+ emitCoherenceWarnings({ ...fingerprint, proxy: proxyOpt, geoip: false, headless: pwOptions.headless, _userArgs: args ?? [], _cacheDirGiven: cacheDir !== undefined,
398
+ _gpuHostMissing: gpuHostMissingFor(fingerprint, identity.identityMode) }, quiet, process.platform, String(RELEASE.version).split(".")[0], advisoryEngineVersion(resolvedEngine, exe));
399
+ const packDir = await fontPackForLaunch(identity.identityMode, resolveFonts, Boolean(quiet));
400
+ const ctxEnv = withShaderDialect(shaderDialect, fontLaunchEnv(exe, opts.env, packDir));
401
+ const dpr = personaDpr(fingerprint);
402
+ // Schema 4 personas travel in a private file inside the profile directory.
403
+ const stagedPersona = await stagePersonaProfile(fingerprint, exe, userDataDir);
404
+ emitPersonaNotices(stagedPersona.notices, quiet);
405
+ const sdkArgs = scaleWindowArgs(fingerprintArgs(stagedPersona.fingerprint, true), dpr, opts.headless === false, personaAvail(fingerprint), userArgs);
406
+ let engineArgs = gateWebrtcArgs(assembleArgs(sdkArgs, extensionArgs(extensions), proxyArgs, disablePrivacySandbox, fingerprint.webrtcIp, userArgs, proxyOpt, socks5Udp, personaPlatformFor(fingerprint)), resolvedEngine, quiet, Boolean(proxyOpt?.server));
407
+ // Native persona/profile geometry only needs viewport:null. A seedless headless launch receives
408
+ // corpus context geometry. Headed mode already set viewport:null above.
409
+ const geom = opts.headless === false
410
+ ? null
411
+ : identity.identityMode === "native"
412
+ ? { mode: "native" }
413
+ : applyHeadlessGeometry(opts, fingerprint.fingerprint, engineArgs);
414
+ if (identity.identityMode === "native" && opts.headless !== false && opts.viewport === undefined) {
415
+ opts.viewport = null;
416
+ }
417
+ engineArgs = initialWindowArgs(engineArgs, geom);
418
+ // A caller's (or the corpus) viewport emulates scale 1; give it the persona's scale.
419
+ Object.assign(opts, withDeviceScale(opts, dpr));
420
+ // Engine patch 0037: the caller's ticket, or one from the local daemon (see ./launch-ticket.ts).
421
+ engineArgs = [...engineArgs, ...ticketArgs];
422
+ // Engine patch 949: the same ticket in ANT0_LAUNCH of the engine child (a copy of the env; never process.env).
423
+ const ticketed = applyTicketEnv(engineArgs, ctxEnv, opts.env);
424
+ engineArgs = withPlaywrightFeatureDefaults(ticketed.args, ignoreDefaultArgs, quiet);
425
+ const childEnv = ticketed.env;
426
+ let context;
427
+ try {
428
+ context = await chromium.launchPersistentContext(userDataDir, {
429
+ ...opts,
430
+ ignoreDefaultArgs, // keep AutomationControlled off (+ component updater on when widevine)
431
+ executablePath: exe,
432
+ ...(childEnv ? { env: childEnv } : {}),
433
+ args: engineArgs,
434
+ });
435
+ }
436
+ catch (error) {
437
+ stagedPersona.removeFile();
438
+ stagedPersona.cleanup(); // a no-op unless userDataDir was "" (a temp persona dir was made)
439
+ rethrowIfTicketRejected(error, launchSecretValues(engineArgs, [userDataDir], childEnv)); // exit 90 / 91 + stderr line -> LaunchTicketRejectedError / PersonaFileRejectedError
440
+ }
441
+ stagedPersona.removeFile(); // the engine read it at startup; nothing may be left in the kept profile
442
+ context.once("close", () => stagedPersona.cleanup());
443
+ installHumanizeOnContext(context, { humanize, showCursor, seed: fingerprint.fingerprint }); // seed => stable motor persona
444
+ return context;
445
+ });
446
+ }
447
+ /** A free ephemeral TCP port on loopback. */
448
+ function freePort() {
449
+ return new Promise((resolve, reject) => {
450
+ const s = createServer();
451
+ s.once("error", reject);
452
+ s.listen(0, "127.0.0.1", () => {
453
+ const addr = s.address();
454
+ const port = typeof addr === "object" && addr ? addr.port : 0;
455
+ s.close(() => resolve(port));
456
+ });
457
+ });
458
+ }
459
+ /**
460
+ * Stale tickets: unlike {@link serve}, a plan cannot retry for you. If your child exits 90 with `claim_expired` or
461
+ * `claim_stale` and the ticket was the SDK-fetched one (you passed no ticket of your own), build a fresh plan (or call
462
+ * `plan.spawn()` again, which fetches a new ticket) and respawn ONCE; do not retry any other reason.
463
+ *
464
+ * Resolve a {@link LaunchPlan} from {@link ServeOptions} without launching anything. This is the
465
+ * first half of {@link serve}; a supervisor spawns `plan.executable` with `plan.args` and
466
+ * `plan.env`, polls `plan.cdpUrl + "/json/version"` for readiness, and removes `plan.userDataDir`
467
+ * on exit when `plan.ownUserDataDir` is true. Side effects: may create the temp profile dir and,
468
+ * on Linux with a persona, resolve (and on first run download) the font pack.
469
+ *
470
+ * Spawn window: the plan carries a launch ticket that engines from ant0.11 accept only for about 5 minutes after it
471
+ * was issued. Spawn the plan promptly, and call `launchPlan` again for every (re)spawn; never respawn from an old plan.
472
+ */
473
+ export async function launchPlan(options = {}) {
474
+ const identity = applyIdentityOption(options);
475
+ options = identity.options;
476
+ const { port, host = "127.0.0.1", allowOrigins, userDataDir: uddOption, headless = true, readyTimeoutMs: _readyTimeoutMs, // consumed by serve()'s readiness loop, not a launch input
477
+ humanize: _humanize, // Playwright-only; not applicable to a direct launch
478
+ showCursor: _showCursor, ...launchOpts } = options;
479
+ // Build the same stealth arg set as launch(); the caller launches the binary directly.
480
+ const { extensions, shaderDialect, socks5Udp, disablePrivacySandbox, executablePath: exeOption, args: callerArgs, cacheDir, quiet, widevine, resolveFonts, launchTicket, engineVersion, runtime, ...rest } = launchOpts;
481
+ const { fingerprint, rest: pwOptions } = splitFingerprintOptions(rest);
482
+ // The resolved proxy (a socks5h:// server is sent as socks5://); throws for a credentialed SOCKS one.
483
+ const { args: proxyArgs, proxy: proxyOpt } = resolveProxy(pwOptions.proxy);
484
+ // Playwright adds --no-sandbox unless chromiumSandbox is true; a direct spawn keeps Chromium's
485
+ // sandbox on by default and drops it only for an explicit false.
486
+ const noSandbox = pwOptions.chromiumSandbox === false;
487
+ const callerEnv = pwOptions.env;
488
+ assertNoReservedArgs(callerArgs ?? []); // before any temp dir, probe or persona file
489
+ let userArgs = callerArgs;
490
+ if (typeof launchTicket === "string" && !hasLaunchTicketArg(userArgs ?? []) && launchTicket.split(".").length !== 5) {
491
+ throw new SdkTypeError("sdk.launch_ticket_invalid", "launchTicket must be the five-segment value the daemon issues");
492
+ }
493
+ return withRuntimeLaunch({ executablePath: exeOption, runtime, launchTicket: manualBinary({ executablePath: exeOption }) ? launchTicket : false, engineVersion, args: argsForTicketDecision(userArgs, callerEnv), quiet }, async ({ executable: exe, ticketArgs, engineVersion: resolvedEngine }) => {
494
+ ensureRunnableHere(exe);
495
+ // Emitted here, not before the engine is resolved: the GPU/canvas gap warnings depend on the engine release.
496
+ emitCoherenceWarnings({ ...fingerprint, proxy: proxyOpt, geoip: false, headless, _userArgs: userArgs ?? [], _cacheDirGiven: cacheDir !== undefined,
497
+ _gpuHostMissing: gpuHostMissingFor(fingerprint, identity.identityMode) }, quiet, process.platform, String(RELEASE.version).split(".")[0], advisoryEngineVersion(resolvedEngine, exe));
498
+ // Env before the temp dir: withShaderDialect throws on a bad dialect, and nothing must leak then.
499
+ // Layered as launch() does: process.env < font wiring < caller env, then the shader dialect.
500
+ const packDir = await fontPackForLaunch(identity.identityMode, resolveFonts, Boolean(quiet));
501
+ const planEnv = (exePath) => {
502
+ // Both helpers already start from process.env and drop what the caller removed; spreading
503
+ // process.env underneath would bring a caller-removed variable back.
504
+ const layered = withShaderDialect(shaderDialect, fontLaunchEnv(exePath, callerEnv, packDir)) ?? process.env;
505
+ const out = {};
506
+ // undefined and null values are dropped (as Python drops None); the rest are stringified.
507
+ for (const [k, v] of Object.entries(layered))
508
+ if (v !== undefined && v !== null)
509
+ out[k] = String(v);
510
+ return out;
511
+ };
512
+ const env = planEnv(exe);
513
+ const resolvedPort = port ?? (await freePort());
514
+ const ownUserDataDir = !uddOption;
515
+ const userDataDir = uddOption ?? mkdtempSync(join(tmpdir(), "ant0-browser-serve-"));
516
+ // From here the plan's own temp dir exists; the caller takes ownership only once the plan is
517
+ // returned, so a throw before that point must remove it (nothing can, otherwise).
518
+ try {
519
+ // widevine: true seeds the CDM into the served profile before the args are built, as
520
+ // launchPersistentContext does (the component-updater switch it may add lands in the args).
521
+ if (widevine)
522
+ userArgs = (await applyWidevineLaunch(userDataDir, undefined, userArgs ?? [], quiet)).args;
523
+ // Ungated on purpose: spawn() resolves the engine again, and the `--webrtc-ip` gate must use
524
+ // the version of the binary that actually starts.
525
+ const stagedServe = await stagePersonaProfile(fingerprint, exe, userDataDir);
526
+ emitPersonaNotices(stagedServe.notices, quiet);
527
+ const rawEngineArgs = assembleArgs(scaleWindowArgs(fingerprintArgs(stagedServe.fingerprint, true), personaDpr(fingerprint), headless === false, personaAvail(fingerprint), userArgs ?? []), extensionArgs(extensions), proxyArgs, disablePrivacySandbox, fingerprint.webrtcIp, userArgs ?? [], proxyOpt, socks5Udp, personaPlatformFor(fingerprint), true);
528
+ const engineArgs = gateWebrtcArgs(rawEngineArgs, resolvedEngine, quiet, Boolean(proxyOpt?.server));
529
+ const origins = allowOrigins ?? `http://${host}:${resolvedPort},http://localhost:${resolvedPort}`;
530
+ // Playwright's launch() adds the first-run hygiene switches itself; a direct spawn must add
531
+ // them, or the first tab is chrome://ungoogled-first-run (see FIRST_RUN_HYGIENE_ARGS).
532
+ const cdpArgs = [
533
+ `--remote-debugging-port=${resolvedPort}`,
534
+ `--remote-debugging-address=${host}`,
535
+ `--remote-allow-origins=${origins}`,
536
+ `--user-data-dir=${userDataDir}`,
537
+ ...FIRST_RUN_HYGIENE_ARGS,
538
+ ];
539
+ if (headless)
540
+ cdpArgs.push("--headless=new");
541
+ if (proxyOpt?.server) {
542
+ cdpArgs.push(`--proxy-server=${proxyOpt.server}`);
543
+ // A caller's own --proxy-bypass-list wins, as it does under Playwright (args come last).
544
+ if (!(userArgs ?? []).some((a) => String(a).startsWith("--proxy-bypass-list")))
545
+ cdpArgs.push(...proxyBypassArgs(proxyOpt));
546
+ }
547
+ if (noSandbox && !(userArgs ?? []).includes("--no-sandbox"))
548
+ cdpArgs.push("--no-sandbox");
549
+ // Chromium opens every positional as a URL; with none from the caller, open about:blank so the
550
+ // first tab is neutral. Appended last so a caller's URL positionals (inside engineArgs) win.
551
+ const startUrlArgs = defaultStartUrlArgs(engineArgs);
552
+ // Engine patch 0037: the caller's ticket (ant0d passes its own in `args`, which wins), or one
553
+ // from the local daemon; the last switch before the start URLs, as the daemon does it.
554
+ let spawned = false;
555
+ // Engine patch 949: the ticket also goes in ANT0_LAUNCH of the engine's environment. The plan's env carries it
556
+ // (a copy; process.env is not touched), so a supervisor that spawns the plan itself passes it on.
557
+ const ticketedPlan = ticketedPlanFor([...engineArgs, ...cdpArgs, ...ticketArgs, ...startUrlArgs], env, callerEnv);
558
+ return {
559
+ executable: exe,
560
+ args: ticketedPlan.args,
561
+ env: ticketedPlan.env,
562
+ userDataDir,
563
+ ownUserDataDir,
564
+ host,
565
+ port: resolvedPort,
566
+ cdpUrl: `http://${host}:${resolvedPort}`,
567
+ identityMode: identity.identityMode,
568
+ headless,
569
+ personaFile: stagedServe.fingerprint.fingerprintProfileFile,
570
+ removePersonaFile: () => stagedServe.removeFile(),
571
+ async spawn(spawnOptions = {}) {
572
+ if (spawned)
573
+ throw new SdkError("sdk.launch_plan_used", "This launch plan has already been used; create a fresh plan");
574
+ spawned = true;
575
+ return withRuntimeLaunch({ executablePath: exeOption, runtime, launchTicket, engineVersion, args: argsForTicketDecision(userArgs, callerEnv), quiet }, async (fresh) => {
576
+ // The engine that starts is the one that was checked: spawn() resolves the binary again, and a
577
+ // different one has not been probed for the persona's format and requirements.
578
+ if (fresh.executable !== exe)
579
+ await assertPersonaFitsEngine(fingerprint.fingerprintProfile, fresh.executable);
580
+ const freshEnv = planEnv(fresh.executable);
581
+ return new Promise((resolve, reject) => {
582
+ const freshPlan = ticketedPlanFor([...gateWebrtcArgs(rawEngineArgs, fresh.engineVersion, true, Boolean(proxyOpt?.server)), ...cdpArgs, ...fresh.ticketArgs, ...startUrlArgs], freshEnv, callerEnv);
583
+ const child = spawn(fresh.executable, freshPlan.args, { ...spawnOptions, env: freshPlan.env, stdio: spawnOptions.stdio ?? ["ignore", "ignore", "pipe"] });
584
+ child.once("error", reject);
585
+ child.once("spawn", () => resolve(child));
586
+ });
587
+ });
588
+ },
589
+ };
590
+ }
591
+ catch (error) {
592
+ if (ownUserDataDir) {
593
+ try {
594
+ rmSync(userDataDir, { recursive: true, force: true });
595
+ }
596
+ catch { /* keep the original error */ }
597
+ }
598
+ else
599
+ removeStalePersonaFile(userDataDir); // the persona file of a plan that never came to be
600
+ throw error;
601
+ }
602
+ });
603
+ }
604
+ /** `applyTicketEnv` for a plan: the env stays a plain string map. */
605
+ function ticketedPlanFor(args, env, callerEnv) {
606
+ const t = applyTicketEnv(args, env, callerEnv);
607
+ const out = {};
608
+ for (const [k, v] of Object.entries(t.env))
609
+ if (v !== undefined)
610
+ out[k] = String(v);
611
+ return { args: t.args, env: out };
612
+ }
613
+ /** Handle for a standing ant0-browser CDP endpoint. Use `.cdpUrl` with any CDP client.
614
+ *
615
+ * Cleanup: call `close()`. Ctrl+C / SIGTERM cleanup is the application's job (the SDK installs no
616
+ * signal handlers). If the process exits without it, an exit hook stops the browser (SIGTERM) and
617
+ * removes the temp profile dir `serve()` created; a `userDataDir` you passed is never deleted. */
618
+ export class Server {
619
+ proc;
620
+ host;
621
+ port;
622
+ userDataDir;
623
+ ownUdd;
624
+ graceMs;
625
+ /** OS process id of the browser (undefined only if the spawn never produced one). */
626
+ pid;
627
+ closing;
628
+ entry;
629
+ constructor(proc, host, port, userDataDir, ownUdd,
630
+ /** @internal How long close() waits after SIGTERM before it falls back to SIGKILL. */
631
+ graceMs = 5000) {
632
+ this.proc = proc;
633
+ this.host = host;
634
+ this.port = port;
635
+ this.userDataDir = userDataDir;
636
+ this.ownUdd = ownUdd;
637
+ this.graceMs = graceMs;
638
+ this.pid = proc.pid;
639
+ this.entry = track(proc, ownUdd ? userDataDir : undefined);
640
+ }
641
+ /** HTTP CDP base — pass to `connectOverCDP` / `puppeteer.connect({ browserURL })`. */
642
+ get cdpUrl() {
643
+ return `http://${this.host}:${this.port}`;
644
+ }
645
+ /** The browser-level WebSocket URL (for clients that want `connect({ browserWSEndpoint })`). */
646
+ async wsUrl() {
647
+ try {
648
+ const r = await fetch(`${this.cdpUrl}/json/version`);
649
+ return (await r.json()).webSocketDebuggerUrl;
650
+ }
651
+ catch {
652
+ return undefined;
653
+ }
654
+ }
655
+ isAlive() {
656
+ return this.proc.exitCode === null && !this.proc.killed;
657
+ }
658
+ /** Stop the browser (SIGTERM, SIGKILL only after a timeout), wait for it to exit, then remove the
659
+ * temp profile dir if serve() created it. The server stays registered for the exit hook until all
660
+ * of that has finished, so `srv.close(); process.exit(0)` without await still cleans up. */
661
+ close() {
662
+ this.closing ??= (async () => {
663
+ await stopChild(this.proc, this.graceMs);
664
+ if (this.ownUdd)
665
+ await removeOwnDir(this.userDataDir);
666
+ untrack(this.entry);
667
+ })();
668
+ return this.closing;
669
+ }
670
+ }
671
+ /**
672
+ * Launch Ant0 Browser with a RAW CDP endpoint and return a {@link Server}. Unlike {@link launch}, `serve`
673
+ * leaves a standing browser any client attaches to with no code change:
674
+ * ```ts
675
+ * const srv = await serve({ identity: { mode: "native" } });
676
+ * const browser = await chromium.connectOverCDP(srv.cdpUrl); // Playwright
677
+ * // or: await puppeteer.connect({ browserURL: srv.cdpUrl }); // Puppeteer
678
+ * // or: point browser-use / Crawl4AI / Stagehand at srv.cdpUrl
679
+ * await srv.close();
680
+ * ```
681
+ * Stays stealthy: the binary is launched **directly** (not through Playwright/Puppeteer), so the
682
+ * `--enable-automation` flag those frameworks add is never present and `navigator.webdriver` stays
683
+ * `false`; the engine's `Runtime.enable` patch (110) stops `Runtime.enable` from running page code
684
+ * (no console-argument serialization, live or replayed, so no getter, Proxy trap or `toString`
685
+ * fires), which removes the best-known CDP tell. It does not make an attached client
686
+ * undetectable: whatever the client itself adds (init scripts, exposed bindings, emulation
687
+ * overrides, other CDP domains) is still its own to hide; the port binds to loopback with an origin
688
+ * allowlist; attaching over CDP adds no launch flags, so the served persona is preserved end to end.
689
+ *
690
+ * First-run hygiene: Playwright's `launch()` passes `--no-first-run`, `--no-default-browser-check`
691
+ * and `--disable-search-engine-choice-screen` on its own; `serve()`/`launchPlan()` add the same
692
+ * three switches (plain UI switches, no `base::Feature` toggles, nothing a page can observe) and,
693
+ * when the caller passes no URL positional in `args`, open `about:blank`. Without them the
694
+ * ungoogled-chromium base opens `chrome://ungoogled-first-run` in the first tab.
695
+ *
696
+ * To own the child process yourself (a daemon supervising exit codes, stderr, kill escalation),
697
+ * call {@link launchPlan} with the same options and spawn from the returned plan instead.
698
+ */
699
+ export async function serve(options = {}) {
700
+ return withTicketRetry((note) => serveOnce({ ...options }, note));
701
+ }
702
+ async function serveOnce(options, note) {
703
+ const { readyTimeoutMs = 30000, quiet } = options;
704
+ const plan = await launchPlan(options);
705
+ // A ticket the SDK fetched (none of the caller's own forms is present) may be retried once if the engine finds it stale.
706
+ note(typeof options.launchTicket !== "string" && options.launchTicket !== false && !hasLaunchTicketArg(options.args ?? [])
707
+ && !callerEnvTicket(options.env) && launchTicketArgValue(plan.args) !== undefined);
708
+ const { host, port: resolvedPort, userDataDir, ownUserDataDir: ownUdd } = plan;
709
+ const dropOwnUdd = () => {
710
+ if (ownUdd) {
711
+ try {
712
+ rmSync(userDataDir, { recursive: true, force: true });
713
+ }
714
+ catch { /* ignore */ }
715
+ }
716
+ };
717
+ // Launched directly, without Playwright or --enable-automation. stderr is piped and drained
718
+ // into a bounded tail so an exit-90 launch-ticket rejection (engine patch 0037) can be named.
719
+ let proc;
720
+ let stderrTail = "";
721
+ try {
722
+ proc = await plan.spawn();
723
+ proc.stderr?.on("data", (chunk) => { stderrTail = (stderrTail + chunk.toString("utf8")).slice(-8192); });
724
+ }
725
+ catch (error) {
726
+ plan.removePersonaFile();
727
+ dropOwnUdd();
728
+ throw redactError(error, launchSecretValues(plan.args, [userDataDir], plan.env)); // a spawn error carries `spawnargs`: the whole command line
729
+ }
730
+ // From here the child and its temp dir are covered by the exit hook (and by abort() below), also
731
+ // while we wait for readiness; the Server takes over the registration once it exists.
732
+ const launch = track(proc, ownUdd ? userDataDir : undefined);
733
+ const abort = async () => {
734
+ plan.removePersonaFile();
735
+ await stopChild(proc, 500);
736
+ if (ownUdd)
737
+ await removeOwnDir(userDataDir);
738
+ untrack(launch);
739
+ };
740
+ const deadline = Date.now() + readyTimeoutMs;
741
+ let ready = false;
742
+ while (Date.now() < deadline) {
743
+ if (proc.exitCode !== null)
744
+ break;
745
+ try {
746
+ await fetch(`${plan.cdpUrl}/json/version`);
747
+ ready = true;
748
+ break;
749
+ }
750
+ catch {
751
+ /* not up yet */
752
+ }
753
+ await new Promise((r) => setTimeout(r, 250));
754
+ }
755
+ if (!ready) {
756
+ await abort();
757
+ const secrets = launchSecretValues(plan.args, [userDataDir], plan.env);
758
+ stderrTail = dropPartialFirstLine(stderrTail, stderrTail.length >= 8192);
759
+ const reason = launchTicketRejection(stderrTail);
760
+ if (reason || proc.exitCode === LAUNCH_TICKET_EXIT_CODE) {
761
+ throw new LaunchTicketRejectedError(reason ?? "missing", redactLaunchSecrets(stderrTail.trim(), secrets));
762
+ }
763
+ const persona = personaFileRejection(stderrTail, proc.exitCode);
764
+ if (persona)
765
+ throw new PersonaFileRejectedError(persona);
766
+ throw new SdkError("sdk.engine_not_ready", `ant0-browser serve: CDP endpoint at ${plan.cdpUrl} did not come up within ${readyTimeoutMs}ms` +
767
+ (proc.exitCode !== null ? ` (engine exited with code ${proc.exitCode})` : "") +
768
+ (stderrTail.trim() ? `\n${redactLaunchSecrets(stderrTail.trim(), secrets)}` : ""));
769
+ }
770
+ plan.removePersonaFile(); // the engine read it at startup
771
+ const srv = new Server(proc, host, resolvedPort, userDataDir, ownUdd);
772
+ untrack(launch);
773
+ if (!quiet) {
774
+ process.stderr.write(`[ant0-browser] CDP endpoint ready: ${srv.cdpUrl}\n` +
775
+ ` attach any client: connectOverCDP(${JSON.stringify(srv.cdpUrl)}) / puppeteer.connect({ browserURL })\n`);
776
+ }
777
+ return srv;
778
+ }
779
+ export default {
780
+ launch,
781
+ launchPersistentContext,
782
+ serve,
783
+ launchPlan,
784
+ Server,
785
+ executablePath,
786
+ fetchWidevine,
787
+ seedWidevine,
788
+ RELEASE,
789
+ };
790
+ //# sourceMappingURL=index.js.map