Playwright.pm 9.3 KB

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