blib/lib/Mojolicious/Plugin/WebComponent.pm

filter: Statementstmt 60.0% 3 / 5 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 2 / 2 Podpod n/a totaltotal 71.4% 5 / 7 CC 1 SCAR 1.4
CC
1
Cov
60%
BEGIN
1.3
BEGIN
1.0
CRAP 1.1
↑ Summary
1 package Mojolicious::Plugin::WebComponent;
2 1 ▶use v5.20;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 0 ▶use Mojo::Base 'Mojolicious::Plugin', -signatures;
Subroutine BEGIN: called CC=1 SCAR=2.6
4 use Carp;
5 use Mojo::JSON qw(to_json);
6 use Mojo::Util qw(decode encode sha1_sum url_escape xml_escape);
7  
8 our $VERSION = "0.08";
9  
10 # a component script is a .js file name, optionally below subfolders; no segment starts with a dot
11 my $SEGMENT = qr/[\w-][\w.-]*/;
12 my $COMPONENT_NAME = qr{\A(?:$SEGMENT/)*$SEGMENT\.js\z}a;
13 my $TEMPLATE_NAME = qr{\A(?:$SEGMENT/)*$SEGMENT\z};
14  
15 has route => sub {
16 my $self = shift;
17 my $root = $self->config->{path} ? $self->config->{path} : '/component';
18 $self->app->routes->any([ qw(HEAD GET) ] => "$root/:checksum/*component")->name('webcomponent')->to(cb => \&_serve);
19 };
20 has 'app';
21 has 'config';
22  
23 sub register($self, $app, $config) {
24 $self->config($config);
25 $self->app($app);
26  
27 my $helper = $config->{helper} // 'component';
28 croak "WebComponent: invalid helper name '$helper'" unless $helper =~ /\A\w+\z/a;
29  
30 if ($app->renderer->helpers->{$helper}) {
31 return $app->log->debug("WebComponent: Helper $helper() is already registered.");
32 }
33  
34 $app->defaults('webcomponent.helper' => $helper);
35  
36 $app->helper($helper => sub {@_ == 1 ? $self : $self->_component(@_)});
37  
38 # create the route now so every worker serves it from the first request, and put it
39 # first so a catch-all route the app declared earlier cannot shadow it
40 my $route = $self->route;
41 my $children = $app->routes->children;
42 @$children = ($route, grep { $_ != $route } @$children);
43 }
44  
45 sub _serve {
46 my $c = shift;
47 my $helper = $c->stash('webcomponent.helper');
48 my $self = $c->$helper;
49  
50 my $component = $c->param('component');
51 return $c->reply->not_found unless defined($component) && $component =~ $COMPONENT_NAME;
52  
53 my $content = $self->_content($c, $component, $self->_getAllParams($c));
54 return $c->reply->not_found unless defined $content;
55  
56 # the url names its content: only a url that still matches may be cached for good,
57 # so a page that links an older version never pins it in a cache
58 my $current = ($c->param('checksum') // '') eq $self->_checksum($content);
59 $c->res->headers->cache_control($current ? 'public, max-age=31536000, immutable' : 'no-cache');
60  
61 # an explicit charset: a script tag otherwise decodes with the page's encoding
62 $c->res->headers->content_type('application/javascript; charset=UTF-8');
63 $c->render(text => $content);
64 }
65  
66 sub _checksum($self, $content) {
67 return sha1_sum(encode('UTF-8', $content));
68 }
69  
70 # The script served for $component with its template injected, or undef when there is no such script.
71 sub _content($self, $c, $component, $params) {
72 my $app = $self->app;
73 my $assetDir = $app->static->asset_dir;
74 my $javascriptPath = $self->config->{javascript_path} ? $self->config->{javascript_path} : "components";
75  
76 my $js = "/$assetDir/js/$javascriptPath/$component";
77 my $asset = $app->static->file($js);
78 return undef unless $asset;
79  
80 my $source = decode('UTF-8', $asset->slurp);
81 die "WebComponent: $component is not valid UTF-8\n" unless defined $source;
82  
83 my $tmpl = $self->_templateScript($c, $component, $params);
84 my $content = '';
85 my $tmplInit = 0;
86 for (split /(?<=\n)/, $source) {
87 if ($tmpl && !$tmplInit) {
88 if ($_ =~ m/let tmpl;/) {
89 $content .= $tmpl;
90 $tmplInit = 1;
91 next;
92 }
93 if ($_ =~ m/shadowRoot.appendChild\(tmpl.content.cloneNode\(true\)\)/) {
94 $content .= $tmpl;
95 $tmplInit = 1;
96 }
97 }
98  
99 $content .= $_;
100 }
101  
102 return $content;
103 }
104  
105 # Is there an html template of this name, as a file or in a DATA section, for any registered handler?
106 sub _templateExists($self, $template) {
107 my $renderer = $self->app->renderer;
108 for my $handler (keys %{$renderer->handlers}) {
109 my $options = {template => $template, format => 'html', handler => $handler};
110 return 1 if defined($renderer->template_path($options)) || defined($renderer->get_data_template($options));
111 }
112 return 0;
113 }
114  
115 # The script that defines `tmpl` for the component, or undef when templating is switched off.
116 sub _templateScript($self, $c, $component, $params) {
117 $params = $params->to_hash;
118 my $templatePath = $self->config->{template_path} ? $self->config->{template_path} : "components";
119  
120 my $templateFile;
121 if (exists($params->{template})) {
122 my $template = $params->{template};
123 $template = $template->[-1] if ref($template) eq 'ARRAY';
124 return undef if !defined($template) || $template =~ m/\A(?:false|f|no|0)\z/i;
125 $templateFile = $template;
126 }
127  
128 # if the template file is not set,
129 $templateFile //= $component =~ s/\.js\z//r;
130  
131 my $tmplHtml;
132 my $label = '';
133 if ($templateFile =~ $TEMPLATE_NAME) {
134 my $template = "$templatePath/$templateFile";
135 $label = xml_escape($template) . ' ';
136 if ($self->_templateExists($template)) {
137 $tmplHtml = $c->render_to_string($template, params => $params);
138 }
139 }
140  
141 # If the template file was not found, show it
142 $tmplHtml //= "<div>404 - ${label}template not found</div>";
143  
144 # one JSON string literal, so template text can never end the string or run code;
145 # the response is a script file, so the "\/" JSON adds for inline use is undone
146 my $literal = to_json("$tmplHtml") =~ s{\\([\\/])}{$1 eq '/' ? '/' : '\\\\'}ger;
147 return "\n let tmpl = document.createElement('template');\n"
148 . " tmpl.innerHTML = $literal;\n ";
149 }
150  
151 sub _component {
152 my $self = shift;
153 my $c = shift;
154 my $name = shift;
155 my $opts = shift;
156 my $route = $self->route;
157  
158 my $base = $c->req->url->base->path->{path};
159 # the base path may come from a proxy header: no trailing slash, and safe inside the quoted attribute
160 $base =~ s{/+\z}{} if defined $base;
161 my $path = $base ? xml_escape($base) . $route->pattern->unparsed
162 : $route->pattern->unparsed;
163  
164 $name .= ".js" if $name !~ m/\.js$/;
165 croak "WebComponent: invalid component name '$name'" unless $name =~ $COMPONENT_NAME;
166  
167 my $params = $self->_getAllParams($c);
168 if (exists($opts->{template})) {
169 $params->param(template => defined($opts->{template}) ? $opts->{template} : 'false');
170 }
171  
172 my $paramString = $params->to_string;
173  
174 # the checksum is that of the script the url will serve; a script or template that
175 # cannot be built here must not break the page, the url then reports it when fetched
176 my $requestId = $opts->{requestId};
177 croak "WebComponent: invalid requestId '$requestId', it cannot contain a slash" if defined($requestId) && $requestId =~ m{/};
178 my $checksum = length($requestId // '') ? url_escape(encode('UTF-8', $requestId)) : do {
179 my $content = eval { $self->_content($c, $name, $params) };
180 $self->app->log->warn("WebComponent: cannot fingerprint $name: $@") if $@;
181 $self->app->log->debug("WebComponent: script $name not found") if !$@ && !defined $content;
182 defined $content ? $self->_checksum($content) : 'unavailable';
183 };
184  
185 # :checksum/:component
186 $path =~ s/:checksum/$checksum/;
187 $path =~ s/\*component/$name/;
188 $path .= "?$paramString" if length($paramString);
189 my $ref = "<script src='$path'></script>";
190  
191 return Mojo::ByteStream->new($ref)
192 }
193  
194 sub _getAllParams($self, $c) {
195 my $rp = $c->req->params->to_hash;
196 # route-internal captures are not parameters of the component
197 my %captures = %{$c->stash->{'mojo.captures'} // {}};
198 delete @captures{qw(cb checksum component)};
199 # sorted, so the same inputs give the same url in every process
200 my %all = (%{$rp}, %captures);
201 return Mojo::Parameters->new(map { $_ => $all{$_} } sort keys %all);
202 }
203  
204 1;
205 __END__
↑ Summary