Playwright.pm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. package Playwright;
  2. use strict;
  3. use warnings;
  4. use v5.28;
  5. use sigtrap qw/die normal-signals/;
  6. use File::pushd;
  7. use File::ShareDir();
  8. use File::Basename();
  9. use Cwd();
  10. use LWP::UserAgent();
  11. use Sub::Install();
  12. use Net::EmptyPort();
  13. use JSON::MaybeXS();
  14. use File::Slurper();
  15. use File::Which();
  16. use Capture::Tiny qw{capture_stderr};
  17. use Carp qw{confess};
  18. use Playwright::Base();
  19. use Playwright::Util();
  20. #ABSTRACT: Perl client for Playwright
  21. no warnings 'experimental';
  22. use feature qw{signatures state};
  23. =head1 SYNOPSIS
  24. use JSON::PP;
  25. use Playwright;
  26. my $handle = Playwright->new();
  27. my $browser = $handle->launch( headless => JSON::PP::false, type => 'chrome' );
  28. my $page = $browser->newPage();
  29. my $res = $page->goto('http://google.com', { waitUntil => 'networkidle' });
  30. my $frameset = $page->mainFrame();
  31. my $kidframes = $frameset->childFrames();
  32. =head1 DESCRIPTION
  33. Perl interface to a lightweight node.js webserver that proxies commands runnable by Playwright.
  34. Checks and automatically installs a copy of the node dependencies in the local folder if needed.
  35. Currently understands commands you can send to all the playwright classes defined in api.json (installed wherever your OS puts shared files for CPAN distributions).
  36. See L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=>
  37. for what the classes do, and their usage.
  38. There are two major exceptions in how things work versus the documentation.
  39. =head2 Selectors
  40. The selector functions have to be renamed from starting with $ for obvious reasons.
  41. The renamed functions are as follows:
  42. =over 4
  43. =item $ => select
  44. =item $$ => selectMulti
  45. =item $eval => eval
  46. =item $$eval => evalMulti
  47. =back
  48. These functions are present as part of the Page, Frame and ElementHandle classes.
  49. =head2 Scripts
  50. The evaluate() and evaluateHandle() functions can only be run in string mode.
  51. To maximize the usefulness of these, I have wrapped the string passed with the following function:
  52. const fun = new Function (toEval);
  53. args = [
  54. fun,
  55. ...args
  56. ];
  57. As such you can effectively treat the script string as a function body.
  58. The same restriction on only being able to pass one arg remains from the upstream:
  59. L<https://playwright.dev/#version=master&path=docs%2Fapi.md&q=pageevaluatepagefunction-arg>
  60. You will have to refer to the arguments array as described here:
  61. L<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments>
  62. =head2 Asynchronous operations
  63. The waitFor* methods defined on various classes will return an instance of L<AsyncData>, a part of the L<Async> module.
  64. You will then need to wait on the result of the backgrounded action with the await() method documented below.
  65. # Assuming $handle is a Playwright object
  66. my $async = $page->waitForEvent('console');
  67. $page->evaluate('console.log("whee")');
  68. my $result = $handle->await( $async );
  69. my $logged = $result->text();
  70. =head1 INSTALLATION NOTE
  71. If you install this module from CPAN, you will likely encounter a croak() telling you to install node module dependencies.
  72. Follow the instructions and things should be just fine.
  73. =head1 CONSTRUCTOR
  74. =head2 new(HASH) = (Playwright)
  75. Creates a new browser and returns a handle to interact with it.
  76. =head3 INPUT
  77. debug (BOOL) : Print extra messages from the Playwright server process
  78. =cut
  79. our ( $spec, $server_bin, $node_bin, %mapper, %methods_to_rename );
  80. sub _check_node {
  81. my $global_install = '';
  82. my $path2here = File::Basename::dirname( Cwd::abs_path( $INC{'Playwright.pm'} ) );
  83. my $decoder = JSON::MaybeXS->new();
  84. # Make sure it's possible to start the server
  85. $server_bin = "$path2here/../bin/playwright_server";
  86. if (!-f $server_bin ) {
  87. $server_bin = File::Which::which('playwright_server');
  88. $global_install = 1;
  89. }
  90. confess("Can't locate Playwright server in '$server_bin'!")
  91. unless -f $server_bin;
  92. #TODO make this portable with File::Which etc
  93. # Check that node and npm are installed
  94. $node_bin = File::Which::which('node');
  95. confess("node must exist and be executable") unless -x $node_bin;
  96. # Check for the necessary modules, this relies on package.json
  97. my $npm_bin = File::Which::which('npm');
  98. confess("npm must exist and be executable") unless -x $npm_bin;
  99. my $dep_raw;
  100. {
  101. #XXX the node Depsolver is deranged, global modules DO NOT WORK
  102. my $curdir = pushd(File::Basename::dirname($server_bin));
  103. capture_stderr { $dep_raw = qx{$npm_bin list --json} };
  104. confess("Could not list available node modules!") unless $dep_raw;
  105. chomp $dep_raw;
  106. my $deptree = $decoder->decode($dep_raw);
  107. my @needed = qw{express uuid yargs playwright};
  108. my @has = keys( %{ $deptree->{dependencies} } );
  109. my @deps = grep {my $subj=$_; grep { $_ eq $subj } @needed } @has;
  110. my $need_deps = scalar(@deps) != scalar(@needed);
  111. #This is really just for developers
  112. if ( $need_deps ) {
  113. confess("Production install of node dependencies must be done manually by nonroot users. Run the following:\n\n pushd '$curdir' && sudo npm i yargs express playwright uuid; popd\n\n") if $global_install;
  114. my $err = capture_stderr { qx{npm i} };
  115. my $exit = $? >> 8;
  116. # Ignore failing for bogus reasons
  117. if ( $err !~ m/package-lock/ ) {
  118. confess("Error installing node dependencies:\n$err") if $exit;
  119. }
  120. }
  121. }
  122. }
  123. sub _build_classes {
  124. $mapper{mouse} = sub {
  125. my ( $self, $res ) = @_;
  126. return Playwright::Mouse->new(
  127. handle => $self,
  128. id => $res->{_guid},
  129. type => 'Mouse'
  130. );
  131. };
  132. $mapper{keyboard} = sub {
  133. my ( $self, $res ) = @_;
  134. return Playwright::Keyboard->new(
  135. handle => $self,
  136. id => $res->{_guid},
  137. type => 'Keyboard'
  138. );
  139. };
  140. %methods_to_rename = (
  141. '$' => 'select',
  142. '$$' => 'selectMulti',
  143. '$eval' => 'eval',
  144. '$$eval' => 'evalMulti',
  145. );
  146. foreach my $class ( keys(%$spec) ) {
  147. $mapper{$class} = sub {
  148. my ( $self, $res ) = @_;
  149. my $class = "Playwright::$class";
  150. return $class->new(
  151. handle => $self,
  152. id => $res->{_guid},
  153. type => $class
  154. );
  155. };
  156. #All of the Playwright::* Classes are made by this MAGIC
  157. Sub::Install::install_sub(
  158. {
  159. code => sub ( $classname, %options ) {
  160. @class::ISA = qw{Playwright::Base};
  161. $options{type} = $class;
  162. return Playwright::Base::new( $classname, %options );
  163. },
  164. as => 'new',
  165. into => "Playwright::$class",
  166. }
  167. ) unless "Playwright::$class"->can('new');;
  168. # Hack in mouse and keyboard objects for the Page class
  169. if ( $class eq 'Page' ) {
  170. foreach my $hid (qw{keyboard mouse}) {
  171. Sub::Install::install_sub(
  172. {
  173. code => sub {
  174. my $self = shift;
  175. $Playwright::mapper{$hid}->(
  176. $self,
  177. {
  178. _type => $self->{type},
  179. _guid => $self->{guid}
  180. }
  181. ) if exists $Playwright::mapper{$hid};
  182. },
  183. as => $hid,
  184. into => "Playwright::$class",
  185. }
  186. ) unless "Playwright::$class"->can($hid);
  187. }
  188. }
  189. # Install the subroutines if they aren't already
  190. foreach my $method ( ( keys( %{ $spec->{$class}{members} } ), 'on' ) ) {
  191. next if grep { $_ eq $method } qw{keyboard mouse};
  192. my $renamed =
  193. exists $methods_to_rename{$method}
  194. ? $methods_to_rename{$method}
  195. : $method;
  196. Sub::Install::install_sub(
  197. {
  198. code => sub {
  199. my $self = shift;
  200. Playwright::Base::_request(
  201. $self,
  202. args => [@_],
  203. command => $method,
  204. object => $self->{guid},
  205. type => $self->{type}
  206. );
  207. },
  208. as => $renamed,
  209. into => "Playwright::$class",
  210. }
  211. ) unless "Playwright::$class"->can($renamed);
  212. }
  213. }
  214. }
  215. sub BEGIN {
  216. our $SKIP_BEGIN;
  217. _check_node() unless $SKIP_BEGIN;
  218. }
  219. sub new ( $class, %options ) {
  220. #XXX yes, this is a race, so we need retries in _start_server
  221. my $port = Net::EmptyPort::empty_port();
  222. my $self = bless(
  223. {
  224. ua => $options{ua} // LWP::UserAgent->new(),
  225. port => $port,
  226. debug => $options{debug},
  227. pid => _start_server( $port, $options{debug} ),
  228. parent => $$,
  229. },
  230. $class
  231. );
  232. $self->_check_and_build_spec();
  233. _build_classes();
  234. return $self;
  235. }
  236. sub _check_and_build_spec ($self) {
  237. return $spec if ref $spec eq 'HASH';
  238. $spec = Playwright::Util::request(
  239. 'GET', 'spec', $self->{port}, $self->{ua},
  240. );
  241. return $spec;
  242. }
  243. =head1 METHODS
  244. =head2 launch(HASH) = Playwright::Browser
  245. The Argument hash here is essentially those you'd see from browserType.launch(). See:
  246. L<https://playwright.dev/#version=v1.5.1&path=docs%2Fapi.md&q=browsertypelaunchoptions>
  247. There is an additional "special" argument, that of 'type', which is used to specify what type of browser to use, e.g. 'firefox'.
  248. =cut
  249. sub launch ( $self, %args ) {
  250. Playwright::Base::_coerce(
  251. $spec->{BrowserType}{members},
  252. args => [ \%args ],
  253. command => 'launch'
  254. );
  255. delete $args{command};
  256. my $msg = Playwright::Util::request(
  257. 'POST', 'session', $self->{port}, $self->{ua},
  258. type => delete $args{type},
  259. args => [ \%args ]
  260. );
  261. return $Playwright::mapper{ $msg->{_type} }->( $self, $msg )
  262. if ( ref $msg eq 'HASH' )
  263. && $msg->{_type}
  264. && exists $Playwright::mapper{ $msg->{_type} };
  265. return $msg;
  266. }
  267. =head2 await (AsyncData) = Object
  268. Waits for an asynchronous operation returned by the waitFor* methods to complete and returns the value.
  269. =cut
  270. sub await ( $self, $promise ) {
  271. confess("Input must be an AsyncData") unless $promise->isa('AsyncData');
  272. my $obj = $promise->result(1);
  273. return $obj unless $obj->{_type};
  274. my $class = "Playwright::$obj->{_type}";
  275. return $class->new(
  276. type => $obj->{_type},
  277. id => $obj->{_guid},
  278. handle => $self
  279. );
  280. }
  281. =head2 quit, DESTROY
  282. Terminate the browser session and wait for the Playwright server to terminate.
  283. Automatically called when the Playwright object goes out of scope.
  284. =cut
  285. sub quit ($self) {
  286. #Prevent destructor from firing in child processes so we can do things like async()
  287. return unless $$ == $self->{parent};
  288. Playwright::Util::request( 'GET', 'shutdown', $self->{port}, $self->{ua} );
  289. return waitpid( $self->{pid}, 0 );
  290. }
  291. sub DESTROY ($self) {
  292. $self->quit();
  293. }
  294. sub _start_server ( $port, $debug ) {
  295. $debug = $debug ? '-d' : '';
  296. $ENV{DEBUG} = 'pw:api' if $debug;
  297. my $pid = fork // confess("Could not fork");
  298. if ($pid) {
  299. print "Waiting for port to come up..." if $debug;
  300. Net::EmptyPort::wait_port( $port, 30 )
  301. or confess("Server never came up after 30s!");
  302. print "done\n" if $debug;
  303. return $pid;
  304. }
  305. exec( $node_bin, $server_bin, "-p", $port, $debug );
  306. }
  307. 1;