lib/BarefootJS.pm

filter: Statementstmt 72.8% 641 / 880 Branchbran 63.5% 407 / 640 Conditioncond 50.5% 142 / 281 MC/DCmcdc 35.7% 59 / 165 Subroutinesub 71.0% 130 / 183 Podpod 0.0% 0 / 117 totaltotal 60.8% 1379 / 2266 CC 487 SCAR 39.3
CC
487
Cov
66%
_has_unsafe_style_value
756.0
reduce
306.0
date
132.0
CRAP 50.9
↑ Summary lib/BarefootJS/Evaluator.pm »
1 package BarefootJS;
2 17 our $VERSION = "0.41.4";
3 17 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 17 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 17 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 17 ▶use feature 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 17 ▶no warnings 'experimental::signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 17 ▶use B ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 17 ▶use JSON::PP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 17 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
12 17 ▶use Time::Local ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 17 ▶use Scalar::Util qw(looks_like_number refaddr weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 17 ▶use BarefootJS::Undefined ();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 17 ▶use BarefootJS::Evaluator ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 # JS `undefined` (BarefootJS/Undefined.pm); Perl's `undef` is JS `null`. A
18 # props hashref has JS's four states for a prop: the key left out (absent),
19 # `$BarefootJS::UNDEF` (present `undefined`), `undef` (`null`) and a value.
20 # `UNDEF` is `defined` in Perl's sense and `//` keeps it, so every nullish
21 # test in this runtime goes through `_nullish` (`is_nullish`), never
22 # `defined` / `//`.
23 17 our $UNDEF = $BarefootJS::Undefined::UNDEF;
24 437 ▶sub _undef_p { BarefootJS::Undefined::is_undefined($_[0]) }
Subroutine _undef_p: called CC=1 SCAR=0.0
25 205 ▶sub _nullish { BarefootJS::Undefined::is_nullish($_[0]) }
Subroutine _nullish: called CC=1 SCAR=0.0
26  
27 # The default of a helper's optional argument: the call passed none. JS
28 # reads an omitted argument as `undefined`, so `_omitted` accepts `UNDEF`
29 # too; an explicit `undef` is JS `null`, which each helper coerces like any
30 # other value (`[1, 2].slice(0, null)` is `[]`).
31 17 my $OMITTED = \'omitted';
32 178 ▶sub _omitted { return (ref $_[0] && refaddr($_[0]) == refaddr($OMITTED)) || _undef_p($_[0]) ? 1 : 0 }
Subroutine _omitted: called CC=4 SCAR=13.9
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] && builtin::refaddr($_[0]) == builtin::refaddr($OMITTED) || _undef_p($_[0]) ? : 52 126 178
Condition100%6/6
ref $_[0] and builtin::refaddr($_[0]) == builtin::refaddr($OMITTED) or _undef_p($_[0])
l!l&&r!l&&!r
3616126
ref $_[0] and builtin::refaddr($_[0]) == builtin::refaddr($OMITTED)
!ll&&!rl&&r
1261636
MC/DC33%1/3
ref $_[0] and builtin::refaddr($_[0]) == builtin::refaddr($OMITTED) or _undef_p($_[0])
ref $_[0] builtin::refaddr($_[0]) == builtin::refaddr($OMITTED) _undef_p($_[0])
Truth table60%3/5
A and B or C
A= ref $_[0]B= builtin::refaddr($_[0]) == builtin::refaddr($OMITTED)C= _undef_p($_[0])
ABCresult
11X1
0X11
1011
0X00
1000
33  
34 # JS ToString / ToNumber for a helper argument (a needle, a separator, a
35 # count), which spell `null` / `undefined` as JS does (`"null"` / 0,
36 # `"undefined"` / NaN); `string` / `number` are the display helpers.
37 98 ▶sub _js_string { BarefootJS::Evaluator::_to_string($_[0]) }
Subroutine _js_string: called CC=1 SCAR=0.0
38 180 ▶sub _js_number { BarefootJS::Evaluator::_to_number($_[0]) }
Subroutine _js_number: called CC=1 SCAR=0.0
39  
40 # NOTE: This runtime is template-engine-agnostic AND framework-agnostic by
41 # design, so it can ship as a standalone CPAN distribution. It depends only on
42 # core Perl (subroutine signatures + the hand-rolled minimal accessor base
43 # below — no Mojo::Base, no Class::Tiny). Every operation that depends on *how*
44 # a template is rendered — JSON marshalling, raw-string marking, JSX-children
45 # materialisation, and named-template rendering — is delegated to a pluggable
46 # `backend` (see BarefootJS::Backend::Mojo for the reference Mojolicious
47 # implementation), which is the only component that pulls in the Mojo
48 # distribution, and only when it is actually used.
49  
50 # ---------------------------------------------------------------------------
51 # Minimal accessor base (no Mojo::Base / Class::Tiny dependency)
52 # ---------------------------------------------------------------------------
53 #
54 # Generates read/write accessors with optional lazy defaults so the runtime
55 # stays free of any non-core OO base. Semantics mirror the Mojo::Base `has`
56 # this class used to inherit: a getter returns the stored value (building it
57 # from the default on first access if unset); a setter stores the value and
58 # returns $self for chaining. A default is either a plain scalar or a coderef
59 # invoked as `$default->($self)` (for per-instance refs like `[]` / `{}` and
60 # the lazily-required Mojo backend).
61 my %ATTR_DEFAULT = (
62 6 ▶ _scripts => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
63 6 ▶ _script_seen => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
64 6 ▶ _preloads => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
65 6 ▶ _preload_seen => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
66 6 ▶ _portal_elements => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
67 10 ▶ _child_renderers => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
68 _is_child => 0,
69 # Lazily fall back to the Mojo reference backend so a bare-blessed
70 # instance (the pure-function unit tests) and the historical
71 # `BarefootJS->new($c, ...)` callers keep working unchanged. A non-Mojo
72 # host injects its own backend via `BarefootJS->new($c, { backend => $b })`
73 # and never triggers this require — keeping the core load Mojo-free.
74 0 ▶ backend => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
75 0 require BarefootJS::Backend::Mojo;
76 0 return BarefootJS::Backend::Mojo->new;
77 },
78 17 );
79  
80 # c — Mojolicious controller (kept for back-compat accessors)
81 # config — plugin / instance config
82 # backend — the template-engine seam (#engine-abstraction)
83 # _scope_id — addressable scope id
84 # _bf_parent / _bf_mount — slot identity when this scope is slot-attached
85 # _props — props serialised into bf-p / the scope comment
86 # _data_key — keyed-loop-item key, emitted as data-key on the scope root
87 17 for my $attr (qw(
88 c config backend
89 _scripts _script_seen _preloads _preload_seen _portal_elements _scope_id _is_child _bf_parent _bf_mount _props
90 _data_key _child_renderers
91 )) {
92 17 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
93 255 ▶ *{"BarefootJS::$attr"} = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
94 363 my $self = shift;
95 363 ▶ if (@_) { $self->{$attr} = shift; return $self; }
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 101 262 363
96 262 ▶ if (!exists $self->{$attr} && exists $ATTR_DEFAULT{$attr}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not exists $self->{$attr} and exists $ATTR_DEFAULT{$attr}) 40 222 262
Condition100%3/3
not exists $self->{$attr} and exists $ATTR_DEFAULT{$attr}
!ll&&!rl&&r
2081440
MC/DC100%2/2
not exists $self->{$attr} and exists $ATTR_DEFAULT{$attr}
not exists $self->{$attr} exists $ATTR_DEFAULT{$attr}
Truth table100%3/3
not(A) and B
A= not exists $self->{$attr}B= exists $ATTR_DEFAULT{$attr}
ABresult
0X0
100
111
97 40 my $d = $ATTR_DEFAULT{$attr};
98 40 ▶ $self->{$attr} = ref($d) eq 'CODE' ? $d->($self) : $d;
Branch: 1 branch
BranchTrueFalseTotal
ref $d eq 'CODE' ? : 40 0 40
99 }
100 262 return $self->{$attr};
101 255 };
102 }
103  
104 29 ▶sub new ($class, $c, $config = {}) {
Subroutine new: called CC=5 SCAR=18.1
Pod undocumented
105 # Build (or accept an injected) rendering backend. The default Mojo
106 # backend wraps the controller and honours an optional `json_encoder`
107 # override so a host can swap in a faster XS JSON implementation
108 # without subclassing. A caller targeting another template engine
109 # passes its own backend via `$config->{backend}`.
110 29 my $backend = $config->{backend};
111 29 ▶ unless ($backend) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($backend) 0 29 29
112 0 require BarefootJS::Backend::Mojo;
113 $backend = BarefootJS::Backend::Mojo->new(
114 c => $c,
115 ($config->{json_encoder}
116 ? (json_encoder => $config->{json_encoder})
117 0 ▶ : ()),
Branch: 1 branch
BranchTrueFalseTotal
$config->{'json_encoder'} ? : 0 0 0
118 );
119 }
120 29 my $self = bless {
121 c => $c,
122 config => $config,
123 backend => $backend,
124 }, $class;
125 # Hold the controller weakly. Mojolicious stashes this bf instance under
126 # `$c->stash->{'bf.instance'}`, so a strong bf -> controller back-reference
127 # closes a per-request cycle ($c -> stash -> bf -> $c) that Perl's
128 # refcount GC cannot reclaim, leaking one controller + bf + child-renderer
129 # closures per request. The controller owns (outlives) the per-request bf,
130 # so the weak ref stays valid for the whole render. Callers that need the
131 # controller to outlive the bf instance independently must keep their own
132 # strong reference (the normal Mojo request scope already does).
133 29 ▶ weaken($self->{c}) if defined $c;
Branch: 1 branch
BranchTrueFalseTotal
if defined $c 1 28 29
134 29 return $self;
135 }
136  
137 # search_params($query = '')
138 #
139 # Build a request-scoped reader for the reactive searchParams() environment
140 # signal (router v0.5, #1922) from a raw query string. Callable as a class or
141 # instance method — the invocant is unused.
142 #
143 # The `require` lives here so consumers (the Mojo plugin, the Xslate host, the
144 # test harness, generated render scripts) reach BarefootJS::SearchParams through
145 # the BarefootJS object they already hold, never `use`-ing it directly — the
146 # same lazy-load seam the Mojo backend uses above. The compiled template reads
147 # the returned object via `$searchParams->get('key')`.
148 9 ▶sub search_params ($invocant, $query = '') {
Subroutine search_params: called CC=2 SCAR=6.9
Pod undocumented
149 9 require BarefootJS::SearchParams;
150 9 return BarefootJS::SearchParams->new($query);
151 }
152  
153 # ---------------------------------------------------------------------------
154 # Scope & Props
155 # ---------------------------------------------------------------------------
156  
157 0 ▶sub scope_attr ($self) {
Subroutine scope_attr: not called CC=2 SCAR=17.9
Pod undocumented
158 # bf-s is the addressable scope id only (#1249).
159 0 ▶ return $self->_scope_id // '';
Condition0%0/2
$self->_scope_id // ""
l!l
00
MC/DC0%0/1
$self->_scope_id // ""
$self->_scope_id
Truth table0%0/2
A
A= $self->_scope_id
Aresult
11
00
160 }
161  
162 # Emits `bf-h="<host>" bf-m="<slot>" bf-r=""` conditionally.
163 # See spec/compiler.md "Slot identity".
164 0 ▶sub hydration_attrs ($self) {
Subroutine hydration_attrs: not called CC=6 SCAR=37.4
Pod undocumented
165 0 my @parts;
166 0 my $host = $self->_bf_parent;
167 0 my $mount = $self->_bf_mount;
168 0 ▶ if (defined $host && length $host) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $host and CORE::length $host) 0 0 0
Condition0%0/3
defined $host and CORE::length $host
!ll&&!rl&&r
000
MC/DC0%0/2
defined $host and CORE::length $host
defined $host CORE::length $host
Truth table0%0/3
A and B
A= defined $hostB= CORE::length $host
ABresult
0X0
100
111
169 0 my $h = $host =~ s/"/&quot;/gr;
170 0 push @parts, qq{bf-h="$h"};
171 }
172 0 ▶ if (defined $mount && length $mount) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $mount and CORE::length $mount) 0 0 0
Condition0%0/3
defined $mount and CORE::length $mount
!ll&&!rl&&r
000
MC/DC0%0/2
defined $mount and CORE::length $mount
defined $mount CORE::length $mount
Truth table0%0/3
A and B
A= defined $mountB= CORE::length $mount
ABresult
0X0
100
111
173 0 my $m = $mount =~ s/"/&quot;/gr;
174 0 push @parts, qq{bf-m="$m"};
175 }
176 0 ▶ unless ($self->_is_child) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->_is_child) 0 0 0
177 0 push @parts, q{bf-r=""};
178 }
179 0 return join(' ', @parts);
180 }
181  
182 # Emits ` data-key="<key>"` for a keyed loop item, else ''. The client
183 # runtime uses data-key for list reconciliation; SSR must match the Hono
184 # reference, which stamps it on each loop item's scope root. The value is set
185 # on the child instance by the child renderer (`register_child_renderer` /
186 # `register_components_from_manifest`) from the JSX `key` prop — a reserved
187 # prop, never a real template variable. The key prints as JS `String(key)`
188 # does (`string`): a JSON boolean row is `true` / `false`, not `1` / `0`.
189 0 ▶sub data_key_attr ($self) {
Subroutine data_key_attr: not called CC=2 SCAR=17.9
Pod undocumented
190 0 my $k = $self->_data_key;
191 0 ▶ return '' if _nullish($k);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($k) 0 0 0
192 0 $k = $self->string($k);
193 0 $k =~ s/&/&amp;/g;
194 0 $k =~ s/"/&quot;/g;
195 0 return qq{ data-key="$k"};
196 }
197  
198 4 ▶sub props_attr ($self) {
Subroutine props_attr: called CC=3 SCAR=11.0
Pod undocumented
199 4 my $props = $self->_props;
200 4 ▶ return '' unless $props && %$props;
Branch: 1 branch
BranchTrueFalseTotal
unless $props and %$props 2 2 4
Condition100%3/3
$props and %$props
!ll&&!rl&&r
112
MC/DC100%2/2
$props and %$props
$props %$props
Truth table100%3/3
A and B
A= $propsB= %$props
ABresult
0X0
100
111
201 # encode_json returns a character string (not bytes) for safe embedding
202 # in templates (the Mojo backend uses Mojo::JSON::to_json).
203 # The JSON must then be attribute-escaped: a raw `'` inside a string
204 # value (e.g. a blog paragraph) terminates the single-quoted attribute
205 # and truncates the hydration payload. The browser entity-decodes the
206 # attribute value, so the client's JSON.parse sees the original text.
207 2 my $json = _html_escape($self->backend->encode_json(_json_ready($props)));
208 2 return qq{ bf-p='$json'};
209 }
210  
211 # ---------------------------------------------------------------------------
212 # Context (SSR mirror of the client `provideContext` / `useContext`)
213 # ---------------------------------------------------------------------------
214 #
215 # A `<Ctx.Provider value>` seeds a value that descendant `useContext(Ctx)`
216 # consumers read during the same render. Dynamic scoping mirrors the client:
217 # the provider pushes the value before rendering its children and pops it
218 # after, and `use_context` reads the innermost active value (or the
219 # `createContext` default when none is active).
220 #
221 # The value stacks live in a package-level store rather than per-instance or
222 # on `$c->stash`: a parent template and the child templates it renders via
223 # `render_child` are separate bf instances that don't reliably share a
224 # controller (the Xslate backend runs with `c => undef`) nor a backend (the
225 # Mojo path lazily builds one per instance). SSR rendering is synchronous —
226 # nothing awaits between a provider's push and its matching pop — and the
227 # push/pop are perfectly balanced, so the per-name stack always unwinds to
228 # empty at the end of each provider subtree, keeping concurrent root renders
229 # isolated. provide/revoke return '' so they drop cleanly into an inline
230 # `<: … :>` (Kolon) or `% … ;` (EP) emit.
231  
232 17 my %CONTEXT_STACKS;
233  
234 0 ▶sub provide_context ($self, $name, $value) {
Subroutine provide_context: not called CC=2 SCAR=17.9
Pod undocumented
235 0 ▶ push @{ $CONTEXT_STACKS{$name} //= [] }, $value;
Condition0%0/2
$CONTEXT_STACKS{$name} //= []
l!l
00
MC/DC0%0/1
$CONTEXT_STACKS{$name} //= []
$CONTEXT_STACKS{$name}
Truth table0%0/2
A
A= $CONTEXT_STACKS{$name}
Aresult
11
00
236 0 return '';
237 }
238  
239 0 ▶sub revoke_context ($self, $name) {
Subroutine revoke_context: not called CC=3 SCAR=24.8
Pod undocumented
240 0 ▶ pop @{ $CONTEXT_STACKS{$name} } if $CONTEXT_STACKS{$name} && @{ $CONTEXT_STACKS{$name} };
Branch: 1 branch
BranchTrueFalseTotal
if $CONTEXT_STACKS{$name} and @{$CONTEXT_STACKS{$name};} 0 0 0
Condition0%0/3
$CONTEXT_STACKS{$name} and @{$CONTEXT_STACKS{$name};}
!ll&&!rl&&r
000
MC/DC0%0/2
$CONTEXT_STACKS{$name} and @{$CONTEXT_STACKS{$name};}
$CONTEXT_STACKS{$name} @{$CONTEXT_STACKS{$name};}
Truth table0%0/3
A and B
A= $CONTEXT_STACKS{$name}B= @{$CONTEXT_STACKS{$name};}
ABresult
0X0
100
111
241 0 return '';
242 }
243  
244 0 ▶sub use_context ($self, $name, $default = $UNDEF) {
Subroutine use_context: not called CC=4 SCAR=30.0
Pod undocumented
245 0 my $stack = $CONTEXT_STACKS{$name};
246 0 ▶ return $default unless $stack && @$stack;
Branch: 1 branch
BranchTrueFalseTotal
unless $stack and @$stack 0 0 0
Condition0%0/3
$stack and @$stack
!ll&&!rl&&r
000
MC/DC0%0/2
$stack and @$stack
$stack @$stack
Truth table0%0/3
A and B
A= $stackB= @$stack
ABresult
0X0
100
111
247 0 return $stack->[-1];
248 }
249  
250 # ---------------------------------------------------------------------------
251 # Comment Markers
252 # ---------------------------------------------------------------------------
253  
254 0 ▶sub comment ($self, $text) {
Subroutine comment: not called CC=1 SCAR=6.9
Pod undocumented
255 0 return "<!--bf-$text-->";
256 }
257  
258 # Neutralize a value for splicing into comment()'s HTML comment content
259 # (#2795 follow-up). comment() itself does no escaping -- fine for every
260 # other caller (marker IDs like "cond-start:s0", "loop:l0", ...), which are
261 # entirely compiler-generated, but the whole-item-conditional loop's
262 # "loop-i:<key>" anchor carries a user-controlled key. Standard HTML
263 # escaping doesn't help inside a comment -- only the literal sequence "-->"
264 # terminates it early, and &/</>/"/' are not special there. The key's exact
265 # text doesn't need to round-trip (the client's mapArrayAnchored matches
266 # items positionally and by its own JS-computed key, never by re-parsing
267 # the anchor Comment.nodeValue), so replacing every "-" with the
268 # visually-similar U+2010 is sufficient and needs no decoding.
269 0 ▶sub escape_comment_key ($self, $value) {
Subroutine escape_comment_key: not called CC=1 SCAR=6.9
Pod undocumented
270 0 my $s = $self->string($value);
271 0 $s =~ s/-/‐/g;
272 0 return $s;
273 }
274  
275 # ---------------------------------------------------------------------------
276 # JS-equivalent value stringification
277 # ---------------------------------------------------------------------------
278  
279 # Map a Perl boolean-shaped value to the JS `String(bool)` form.
280 # Used by the Mojo adapter when emitting reactive attribute bindings
281 # whose JS source `isBooleanResultExpr` classified as boolean —
282 # a comparison (`count() > 0`), a logical negation (`!ok()`), or a
283 # literal `true` / `false`. Perl's auto-stringification of those
284 # expressions yields `''` / `1`; Hono and Go emit `'false'` / `'true'`.
285 # Centralising the bool → string mapping here keeps the contract
286 # testable and the template-emit syntax tidy
287 # (`<%= bf->bool_str(...) %>` vs an inline ternary).
288 #
289 # Contract is boolean-only: callers must have classified the
290 # expression as boolean-result before routing through this helper.
291 # Non-boolean values reaching here will be Perl-truthy-coerced to
292 # 'true' / 'false', which is generally wrong — non-boolean attribute
293 # bindings stay on the plain `<%= expr %>` emit path and never reach
294 # this function.
295 3 ▶sub bool_str ($self, $value) {
Subroutine bool_str: called CC=6 SCAR=19.0
Pod undocumented
296 # An already-stringified JS boolean (`String(flag)`, which `string`
297 # prints as `true` / `false`, #3440) keeps its text: the string
298 # `'false'` is truthy in Perl.
299 3 ▶ return $value if defined $value && !ref($value) && ($value eq 'true' || $value eq 'false');
Branch: 1 branch
BranchTrueFalseTotal
if defined $value and not ref $value and $value eq "true" || $value eq "false" 2 1 3
Condition66%6/9
defined $value and not ref $value and $value eq "true" || $value eq "false"
!ll&&!rl&&r
012
defined $value and not ref $value
!ll&&!rl&&r
003
$value eq "true" or $value eq "false"
l!l&&r!l&&!r
111
MC/DC50%2/4
defined $value and not ref $value and $value eq "true" || $value eq "false"
defined $value not ref $value $value eq "true" $value eq "false"
Truth table60%3/5
A and not(B) and C or D
A= defined $valueB= not ref $valueC= $value eq "true"D= $value eq "false"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
300 1 ▶ return $value ? 'true' : 'false';
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 0 1 1
301 }
302  
303 0 ▶sub text_start ($self, $slot_id) {
Subroutine text_start: not called CC=1 SCAR=6.9
Pod undocumented
304 0 return "<!--bf:$slot_id-->";
305 }
306  
307 0 ▶sub text_end ($self) {
Subroutine text_end: not called CC=1 SCAR=6.9
Pod undocumented
308 0 return "<!--/-->";
309 }
310  
311 # See spec/compiler.md "Slot identity" for the comment-scope wire format.
312 5 ▶sub scope_comment ($self) {
Subroutine scope_comment: called CC=7 SCAR=19.6
Pod undocumented
313 5 ▶ my $scope_id = $self->_scope_id // '';
Condition100%2/2
$self->_scope_id // ""
l!l
41
MC/DC100%1/1
$self->_scope_id // ""
$self->_scope_id
Truth table100%2/2
A
A= $self->_scope_id
Aresult
11
00
314 5 my $host_segment = '';
315 5 my $host = $self->_bf_parent;
316 5 my $mount = $self->_bf_mount;
317 5 ▶ if (defined $host && length $host) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $host and CORE::length $host) 2 3 5
Condition66%2/3
defined $host and CORE::length $host
!ll&&!rl&&r
302
MC/DC50%1/2
defined $host and CORE::length $host
defined $host CORE::length $host
Truth table66%2/3
A and B
A= defined $hostB= CORE::length $host
ABresult
0X0
100
111
318 2 ▶ $host_segment = "|h=$host|m=" . ($mount // '');
Condition50%1/2
$mount // ""
l!l
20
MC/DC0%0/1
$mount // ""
$mount
Truth table50%1/2
A
A= $mount
Aresult
11
00
319 }
320 5 my $props_json = '';
321 5 ▶ if ($self->_props && %{$self->_props}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_props and %{$self->_props;}) 3 2 5
Condition66%2/3
$self->_props and %{$self->_props;}
!ll&&!rl&&r
203
MC/DC50%1/2
$self->_props and %{$self->_props;}
$self->_props %{$self->_props;}
Truth table66%2/3
A and B
A= $self->_propsB= %{$self->_props;}
ABresult
0X0
100
111
322 3 $props_json = '|' . $self->backend->encode_json(_json_ready($self->_props));
323 }
324 5 return "<!--bf-scope:$scope_id$host_segment$props_json-->";
325 }
326  
327 # Paired end marker for scope_comment above. Bounds the scope's sibling
328 # range so client-side queries from a fragment-rooted scope don't leak
329 # onto later siblings owned by the parent (#2289). No `|h=`/`|m=`/props
330 # segments — the client only needs the scope id to find the matching end.
331 3 ▶sub scope_comment_end ($self) {
Subroutine scope_comment_end: called CC=2 SCAR=6.9
Pod undocumented
332 3 ▶ my $scope_id = $self->_scope_id // '';
Condition100%2/2
$self->_scope_id // ""
l!l
21
MC/DC100%1/1
$self->_scope_id // ""
$self->_scope_id
Truth table100%2/2
A
A= $self->_scope_id
Aresult
11
00
333 3 return "<!--bf-/scope:$scope_id-->";
334 }
335  
336 # ---------------------------------------------------------------------------
337 # Script Registration
338 # ---------------------------------------------------------------------------
339  
340 0 ▶sub register_script ($self, $path) {
Subroutine register_script: not called CC=2 SCAR=17.9
Pod undocumented
341 0 ▶ return if $self->_script_seen->{$path};
Branch: 1 branch
BranchTrueFalseTotal
if $self->_script_seen->{$path} 0 0 0
342 0 $self->_script_seen->{$path} = 1;
343 0 push @{$self->_scripts}, $path;
344 }
345  
346 # Register a `<link rel="modulepreload">` hint — mirrors register_script
347 # exactly: same dedup-by-path hash, same insertion-order arrayref, same
348 # lifetime/reset (child-propagation) semantics, same no-output-string
349 # return so a template's `<: $bf->register_preload(...) :>` /
350 # `% $bf->register_preload(...);` emits no bytes where it sits. The
351 # `<link>` tag itself is only ever produced by `scripts` below, never
352 # here — a preload registration must never inject a node into a
353 # component's own template output.
354 0 ▶sub register_preload ($self, $path) {
Subroutine register_preload: not called CC=2 SCAR=17.9
Pod undocumented
355 0 ▶ return if $self->_preload_seen->{$path};
Branch: 1 branch
BranchTrueFalseTotal
if $self->_preload_seen->{$path} 0 0 0
356 0 $self->_preload_seen->{$path} = 1;
357 0 push @{$self->_preloads}, $path;
358 }
359  
360 # ---------------------------------------------------------------------------
361 # SSR Portal Element Registration (#3119)
362 # ---------------------------------------------------------------------------
363  
364 # Collects an `ssrPortalOwnerScope`-flagged element's already-rendered,
365 # fully-evaluated markup so it can be emitted at the `portals` outlet near
366 # `</body>` instead of at its source position — the `ref`-callback
367 # SSR-portal pattern the dialog-style primitives use
368 # (`DialogOverlay`/`DialogContent`, `DropdownMenuContent`,
369 # `PopoverContent`, the explicit `<Portal>` component). `$content` already
370 # carries its own `bf-po` attribute (stamped directly on its own tag by the
371 # compiler, matching exactly what the client
372 # `createPortal(el, document.body, { ownerScope })` stamps onto the SAME
373 # element at hydrate time), so unlike a hypothetical "wrap arbitrary
374 # children" collector this appends `$content` UNWRAPPED — no extra
375 # `bf-pi`/`bf-po` container element, which would diverge from what the
376 # client stamps directly onto the element itself. Returns nothing — every
377 # call site sinks the return value (a template's `% $bf->register_portal_
378 # element(...);` statement tag / Kolon `: $bf.register_portal_element(...)
379 # ;`, never an output tag), so nothing prints at the source position.
380 0 ▶sub register_portal_element ($self, $content) {
Subroutine register_portal_element: not called CC=1 SCAR=6.9
Pod undocumented
381 0 push @{$self->_portal_elements}, $content;
382 0 return;
383 }
384  
385 # Emits every collected SSR-portal element, in registration order. Place
386 # `<%= $bf->portals %>` (Mojo) / `: $bf.portals()` (Kolon) once near
387 # `</body>` in the app's own layout — mirrors `scripts` above (same
388 # "collect during render, emit at a single outlet" shape) and the Hono
389 # reference adapter's `<BfPortals />`.
390 0 ▶sub portals ($self) {
Subroutine portals: not called CC=1 SCAR=6.9
Pod undocumented
391 0 return join "\n", @{$self->_portal_elements};
392 }
393  
394 # ---------------------------------------------------------------------------
395 # Child Component Rendering
396 # ---------------------------------------------------------------------------
397 # (`_child_renderers` accessor is generated by the minimal accessor base above.)
398  
399 # Register a renderer for `render_child($name, ...)`. The renderer is
400 # invoked as `$renderer->($props_hashref, $invoking_bf)` — unpack `@_`
401 # (`my ($props, $caller) = @_;`) instead of declaring a one-argument
402 # subroutine signature, which would enforce arity and die on the second
403 # argument.
404 26 ▶sub register_child_renderer ($self, $name, $renderer) {
Subroutine register_child_renderer: called CC=1 SCAR=0.0
Pod undocumented
405 26 $self->_child_renderers->{$name} = $renderer;
406 }
407  
408 # The keys the innermost `render_child` call passed (see `passed`); undef
409 # outside one, i.e. while the root renders.
410 17 our $CALLER_KEYS;
411  
412 # Whether this component's caller passed the prop `$name`, even as undef
413 # (`null`) or `UNDEF`: JS's `name in props`, which a template can't ask of its
414 # stash (every declared prop is seeded, so an omitted one reads as its default
415 # or `UNDEF`, as a present `undefined` one does). A `{...props}` spread onto a
416 # child carries a param only when this is true. The keys are those
417 # `render_child` recorded for a child and `_props` for the root; with neither
418 # recorded (a root rendered without `_props`), `$fallback`, the template's own
419 # "not undefined" test, decides.
420 11 ▶sub passed ($self, $name, $fallback = undef) {
Subroutine passed: called CC=7 SCAR=19.5
Pod undocumented
421 11 ▶ return exists $CALLER_KEYS->{$name} ? 1 : 0 if $CALLER_KEYS;
Branch: 2 branches
BranchTrueFalseTotal
if $BarefootJS::CALLER_KEYS 3 8 11
exists $BarefootJS::CALLER_KEYS->{$name} ? : 2 1 3
422 8 my $props = $self->_props;
423 8 ▶ return exists $props->{$name} ? 1 : 0 if ref $props eq 'HASH';
Branch: 2 branches
BranchTrueFalseTotal
if ref $props eq "HASH" 5 3 8
exists $props->{$name} ? : 3 2 5
424 3 ▶ return $fallback ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$fallback ? : 1 2 3
425 }
426  
427 16 ▶sub render_child ($self, $name, @args) {
Subroutine render_child: called CC=5 SCAR=16.1
Pod undocumented
428 16 my $renderer = $self->_child_renderers->{$name};
429 16 ▶ die "No renderer registered for child component '$name'" unless $renderer;
Branch: 1 branch
BranchTrueFalseTotal
unless $renderer 1 15 16
430 # Accept both the Mojo list form — `bf->render_child($name, k => v, ...)`
431 # — and the single-hashref form — `$bf.render_child($name, { k => v })`.
432 # Template languages whose method calls can't splat a hash into positional
433 # args (Text::Xslate Kolon, Template Toolkit) pass one hashref instead.
434 15 ▶ my %props = (@args == 1 && ref $args[0] eq 'HASH') ? %{ $args[0] } : @args;
Branch: 1 branch
BranchTrueFalseTotal
@args == 1 && ref $args[0] eq 'HASH' ? : 2 13 15
Condition66%2/3
@args == 1 and ref $args[0] eq "HASH"
!ll&&!rl&&r
1302
MC/DC50%1/2
@args == 1 and ref $args[0] eq "HASH"
@args == 1 ref $args[0] eq "HASH"
Truth table66%2/3
A and B
A= @args == 1B= ref $args[0] eq "HASH"
ABresult
0X0
100
111
435 # JSX children AND any other named JSX-valued slot (`header={<strong/>}`,
436 # #2168 jsx-element-prop) come in via the engine's children-capture
437 # mechanism (Mojo's `begin %>...<% end`, which produces a CODE ref
438 # returning a Mojo::ByteStream). Materialize every prop value through
439 # the backend before handing the props to the child renderer, so the
440 # child template sees each slot as already-rendered HTML rather than a
441 # bare CODE ref — `materialize` is a no-op for a value that isn't a
442 # CODE ref (see e.g. `BarefootJS::Backend::Mojo::materialize`), so this
443 # is safe to apply unconditionally rather than naming `children`
444 # specifically.
445 15 $props{$_} = $self->backend->materialize($props{$_}) for keys %props;
446 # Record the keys this call passes for the child's `passed` while its
447 # template renders. The renderer builds the child's own instance, so the
448 # record is dynamically scoped (`local`) rather than stored on that
449 # object; rendering is synchronous, so it always holds the keys of the
450 # component whose template is running.
451 15 local $CALLER_KEYS = { map { $_ => 1 } keys %props };
452 # Renderer contract (#1897): the renderer is invoked with TWO
453 # arguments — the props hashref and the INVOKING instance. A renderer
454 # registered on the root may be called from a nested child render
455 # (AccordionTrigger -> ChevronDownIcon), and the grandchild's scope /
456 # slot identity must chain off the CALLER's scope id, not the
457 # registrant's. Renderers unpack `@_` (`my ($props, $caller) = @_;`)
458 # rather than enforcing arity with a one-arg subroutine signature —
459 # see `register_child_renderer`.
460 15 return $renderer->(\%props, $self);
461 }
462  
463 # ---------------------------------------------------------------------------
464 # Bulk registration from build manifest
465 # ---------------------------------------------------------------------------
466 #
467 # `vite build` (via `@barefootjs/mojolicious/vite`'s `barefoot()` plugin)
468 # emits dist/templates/manifest.json describing every component the page
469 # might invoke (Counter, ui/button/index, ...).
470 # This helper walks that manifest and registers one child renderer per
471 # UI registry entry — the path shape `ui/<name>/index` maps to the
472 # `<name>` slot key Counter.html.ep and friends use via
473 # `<%= bf->render_child('<name>', ...) %>`.
474 #
475 # Each manifest entry carries an `ssrDefaults` hash derived statically
476 # from the component's JSX (prop destructure defaults + signal /
477 # memo initial values, see packages/jsx/src/ssr-defaults.ts). The
478 # child renderer seeds every template variable from that hash,
479 # preferring the caller's matching prop where one exists. This
480 # replaces the per-component `signal_init` callback that every
481 # scaffold's `app.pl` used to hand-roll for items 1/3 of issue #1416.
482 #
483 # `signal_init` remains as an opt-in override for cases the static
484 # extractor can't see through (e.g. signal initial values that
485 # reference imported helpers). When supplied for a given slot key
486 # it takes precedence over the manifest's `ssrDefaults` for that
487 # child, allowing callers to mix manual overrides with auto-derived
488 # defaults for siblings.
489 #
490 # Multi-component modules (#2132): a registry module exporting several
491 # components from one file (`ui/toast/index.tsx` → ToastProvider, Toast,
492 # ToastTitle, ...) compiles to one template PER component, listed in the
493 # entry's `components` map (`{ ToastProvider => { markedTemplate,
494 # ssrDefaults }, ... }`). Compiled parent templates invoke each one under
495 # its snake_cased component name (`render_child('toast_provider')`), so a
496 # renderer is registered per component. These run AFTER the directory-name
497 # registration and win on collision — for `ui/toast/index` the key `toast`
498 # must resolve to Toast's own template, not the module's first template
499 # (ToastProvider), which is all the bare `markedTemplate` carries.
500 7 ▶sub register_components_from_manifest ($self, $manifest, %opts) {
Subroutine register_components_from_manifest: called CC=8 SCAR=20.9
Pod undocumented
501 7 ▶ my $signal_inits = $opts{signal_init} // {};
Condition100%2/2
$opts{"signal_init"} // {}
l!l
16
MC/DC100%1/1
$opts{"signal_init"} // {}
$opts{"signal_init"}
Truth table100%2/2
A
A= $opts{"signal_init"}
Aresult
11
00
502  
503 7 for my $entry_name (keys %$manifest) {
504 # `__barefoot__` is the runtime entry, not a component.
505 7 ▶ next if $entry_name eq '__barefoot__';
Branch: 1 branch
BranchTrueFalseTotal
if $entry_name eq "__barefoot__" 0 7 7
506 # Only UI registry components (path shape `ui/<name>/index`)
507 # become child renderers; top-level page components are the
508 # render target rather than a child.
509 7 ▶ next unless $entry_name =~ m{^ui/([^/]+)/index$};
Branch: 1 branch
BranchTrueFalseTotal
unless $entry_name =~ m[^ui/([^/]+)/index$] 0 7 7
510 7 my $slot_key = $1;
511 7 my $entry = $manifest->{$entry_name};
512  
513 # Directory-name registration — the pre-`components` convention,
514 # kept so manifests from older builds (no `components` map) still
515 # resolve single-component modules like `button`.
516 $self->_register_manifest_child(
517 $slot_key, $entry->{markedTemplate},
518 $signal_inits->{$slot_key}, $entry->{ssrDefaults},
519 7 );
520  
521 # Per-component registrations (#2132), keyed by the snake_cased
522 # component name the compiled templates actually call.
523 7 my $components = $entry->{components};
524 7 ▶ next unless ref($components) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $components eq "HASH" 2 5 7
525 5 for my $component_name (sort keys %$components) {
526 16 my $component = $components->{$component_name};
527 16 ▶ next unless ref($component) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $component eq "HASH" 0 16 16
528 16 my $component_key = _snake_case($component_name);
529 $self->_register_manifest_child(
530 $component_key, $component->{markedTemplate},
531 $signal_inits->{$component_key}, $component->{ssrDefaults},
532 16 );
533 }
534 }
535 }
536  
537 # Random suffix for a scope id with no slot to derive it from
538 # (`<Template>_<suffix>`). Always six digits: stringifying `rand()` and
539 # stripping its `0.` breaks when Perl prints a small value in exponent form
540 # (`3.2247e-05` -> `3.2247`), which put a `.` into the id. Every Perl-side
541 # producer of such an id calls this, so they cannot drift apart.
542 10013 ▶sub scope_id_suffix () {
Subroutine scope_id_suffix: called CC=1 SCAR=0.0
Pod undocumented
543 10013 return sprintf('%06d', int(rand(1_000_000)));
544 }
545  
546 # PascalCase → snake_case, mirroring the Mojo adapter's `toTemplateName`
547 # (prefix every uppercase letter with `_`, lowercase the whole string,
548 # strip the leading `_`): `ToastProvider` → `toast_provider`.
549 20 ▶sub _snake_case ($name) {
Subroutine _snake_case: called CC=1 SCAR=0.0
550 20 my $s = $name;
551 20 $s =~ s/([A-Z])/_$1/g;
552 20 $s = CORE::lc $s;
553 20 $s =~ s/^_//;
554 20 return $s;
555 }
556  
557 # Register one manifest-driven child renderer: `$slot_key` becomes the
558 # `render_child` name, `$marked` locates the template, and `$signal_init`
559 # / `$manifest_defaults` seed the child's template vars (see
560 # `register_components_from_manifest` for the contract).
561 23 ▶sub _register_manifest_child ($self, $slot_key, $marked, $signal_init, $manifest_defaults) {
Subroutine _register_manifest_child: called CC=3 SCAR=11.2
562 23 ▶ $marked //= '';
Condition100%2/2
$marked //= ""
l!l
221
MC/DC100%1/1
$marked //= ""
$marked
Truth table100%2/2
A
A= $marked
Aresult
11
00
563 23 ▶ return unless $marked;
Branch: 1 branch
BranchTrueFalseTotal
unless $marked 1 22 23
564 22 my $parent_scope = $self->_scope_id;
565 # Weaken the parent capture so the child-renderer closures stored on
566 # `$self->_child_renderers` don't keep `$self` alive (the direct
567 # closure <-> parent cycle). The controller is reached through `$parent`
568 # at call time rather than captured strongly here, so the closures hold
569 # no strong reference to `$c` either — see the controller-cycle note in
570 # `new`. `$parent` is always live whenever a closure runs (the closure is
571 # stored on `$parent`, so `$parent` outlives every invocation).
572 22 weaken(my $parent = $self);
573  
574 # `templates/ui/button/index.html.ep` → `ui/button/index`
575 22 my $template_name = $marked;
576 22 $template_name =~ s{^templates/}{};
577 22 $template_name =~ s{\.html\.ep$}{};
578  
579 10 ▶ $self->register_child_renderer($slot_key, sub {
Subroutine __ANON__: called CC=8 SCAR=21.9
580 # `$caller` is the instance whose template invoked
581 # `render_child` (#1897) — for a nested render that is a child
582 # instance, and the grandchild's scope/slot identity must chain
583 # off ITS scope id (`root_s0_s0`), not the registrant's.
584 10 my ($props, $caller) = @_;
585 10 ▶ my $host = $caller // $parent;
Condition33%1/3
$caller // $parent
l!l&&r!l&&!r
1000
MC/DC0%0/2
$caller // $parent
$caller $parent
Truth table33%1/3
A // B
A= $callerB= $parent
ABresult
1X1
011
000
586 10 ▶ my $host_scope = $host->_scope_id // $parent_scope;
Condition33%1/3
$host->_scope_id // $parent_scope
l!l&&r!l&&!r
1000
MC/DC0%0/2
$host->_scope_id // $parent_scope
$host->_scope_id $parent_scope
Truth table33%1/3
A // B
A= $host->_scope_idB= $parent_scope
ABresult
1X1
011
000
587 # Child shares the parent's backend so nested renders go
588 # through the same engine + controller (and inherit any
589 # injected json_encoder). The controller is fetched via the weak
590 # `$parent` at call time — never captured strongly — so the
591 # closure adds no edge to the per-request reference cycle.
592 10 my $child_bf = BarefootJS->new($parent->c, { backend => $parent->backend });
593 10 my $slot_id = delete $props->{_bf_slot};
594 # JSX `key` (a reserved prop) → data-key on the child's scope root
595 # for keyed-loop reconciliation (see `data_key_attr`).
596 10 my $data_key = delete $props->{key};
597 10 ▶ $child_bf->_data_key($data_key) unless _nullish($data_key);
Branch: 1 branch
BranchTrueFalseTotal
unless _nullish($data_key) 0 10 10
598 10 ▶ $child_bf->_scope_id(
Branch: 1 branch
BranchTrueFalseTotal
$slot_id ? : 0 10 10
599 $slot_id ? $host_scope . '_' . $slot_id
600 : $template_name . '_' . scope_id_suffix()
601 );
602 10 $child_bf->_is_child(1);
603 # (#1249) Slot identity: host scope + slot id. Emitted as
604 # bf-h / bf-m attributes by hydration_attrs.
605 10 ▶ if ($slot_id) {
Branch: 1 branch
BranchTrueFalseTotal
if ($slot_id) 0 10 10
606 0 $child_bf->_bf_parent($host_scope);
607 0 $child_bf->_bf_mount($slot_id);
608 }
609 # Share the root registry so the child's own template can
610 # render further imported components (#1897).
611 10 $child_bf->_child_renderers($parent->_child_renderers);
612 10 $child_bf->_scripts($parent->_scripts);
613 10 $child_bf->_script_seen($parent->_script_seen);
614 10 $child_bf->_preloads($parent->_preloads);
615 10 $child_bf->_preload_seen($parent->_preload_seen);
616 # Shares the SAME root-level arrayref as `_scripts` above — every
617 # child renderer registered here closes over `$parent` (the
618 # instance `register_components_from_manifest` was called on, the
619 # page root), so this reaches ANY "use client" nesting depth for
620 # free, unlike the Go adapter's `PropagatePortals`, which needed an
621 # explicit recursive walk because Go structs copy fields by value
622 # rather than sharing a mutable reference (#3119).
623 10 $child_bf->_portal_elements($parent->_portal_elements);
624  
625 10 my %extra;
626 10 ▶ if ($signal_init) {
Branch: 2 branches
BranchTrueFalseTotal
if ($signal_init) { } 1 9 10
elsif ($manifest_defaults) { } 9 0 9
627 1 %extra = $signal_init->($props);
628 } elsif ($manifest_defaults) {
629 9 %extra = _derive_stash_from_defaults($manifest_defaults, $props);
630 }
631  
632 # Render the child template with $child_bf bound as the active
633 # instance for the nested render. The backend owns the
634 # engine-specific binding + restore (stash juggle for Mojo).
635 10 my $html = $parent->backend->render_named(
636 $template_name, $child_bf, { %$props, %extra },
637 );
638 10 chomp $html;
639 10 return $html;
640 22 });
641 }
642  
643 # Derive template-stash kvs from a manifest entry's `ssrDefaults`
644 # section. Each entry shape:
645 # { value => <static-fallback>, propName => <prop>, isRestProps => bool }
646 # For `isRestProps`, the rest bag passes through unchanged (or the
647 # static `{}` if the caller didn't supply one). For ordinary entries
648 # the caller's `$props->{propName}` wins when present -- `undef` (JS `null`)
649 # included -- and an absent or `UNDEF` prop takes the static `value`, or
650 # `UNDEF` when the entry has none (the manifest writes `value` only for a
651 # prop with a default; spec/js-undefined-value.md, decision 6).
652 # `propName`-less entries (signal / memo locals) always use the static
653 # value — the caller cannot override them.
654 21 ▶sub _derive_stash_from_defaults ($defaults, $props) {
Subroutine _derive_stash_from_defaults: called CC=8 SCAR=21.0
655 21 my %extra;
656 21 for my $name (keys %$defaults) {
657 37 my $d = $defaults->{$name};
658 37 ▶ if (ref($d) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $d ne "HASH") 0 37 37
659 0 $extra{$name} = BarefootJS::Undefined::decode_undefined($d);
660 0 next;
661 }
662 37 ▶ if ($d->{isRestProps}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d->{"isRestProps"}) 4 33 37
663 4 ▶ $extra{$name} = exists $props->{$name} ? $props->{$name} : _static_fallback($d);
Branch: 1 branch
BranchTrueFalseTotal
exists $props->{$name} ? : 1 3 4
664 4 next;
665 }
666 33 my $prop_name = $d->{propName};
667 33 ▶ if (defined $prop_name && exists $props->{$prop_name} && !_undef_p($props->{$prop_name})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $prop_name and exists $props->{$prop_name} and not _undef_p($props->{$prop_name})) { } 6 27 33
Condition83%5/6
defined $prop_name and exists $props->{$prop_name} and not _undef_p($props->{$prop_name})
!ll&&!rl&&r
2436
defined $prop_name and exists $props->{$prop_name}
!ll&&!rl&&r
0249
MC/DC66%2/3
defined $prop_name and exists $props->{$prop_name} and not _undef_p($props->{$prop_name})
defined $prop_name exists $props->{$prop_name} not _undef_p($props->{$prop_name})
Truth table75%3/4
A and B and not(C)
A= defined $prop_nameB= exists $props->{$prop_name}C= not _undef_p($props->{$prop_name})
ABCresult
0XX0
10X0
1100
1111
668 6 $extra{$name} = $props->{$prop_name};
669 } else {
670 27 $extra{$name} = _static_fallback($d);
671 }
672 }
673 21 return %extra;
674 }
675  
676 # An `ssrDefaults` entry's seed when the caller's prop is absent or `UNDEF`:
677 # its `value` (a `{"$undef": true}` sentinel in it is `UNDEF`), or `UNDEF`
678 # when it has none.
679 30 ▶sub _static_fallback ($d) {
Subroutine _static_fallback: called CC=2 SCAR=6.9
680 30 ▶ return exists $d->{value} ? BarefootJS::Undefined::decode_undefined($d->{value}) : $UNDEF;
Branch: 1 branch
BranchTrueFalseTotal
exists $d->{'value'} ? : 21 9 30
681 }
682  
683 # ---------------------------------------------------------------------------
684 # Script Output
685 # ---------------------------------------------------------------------------
686  
687 0 ▶sub scripts ($self) {
Subroutine scripts: not called CC=3 SCAR=24.8
Pod undocumented
688 0 my @tags;
689 # Preload hints BEFORE script tags — a hint that arrives after the
690 # script it describes is useless. Same escaping (none; paths are
691 # caller-trusted resolved URLs) as the script tags below.
692 0 for my $path (@{$self->_preloads}) {
693 0 push @tags, qq{<link rel="modulepreload" crossorigin href="$path">};
694 }
695 0 for my $path (@{$self->_scripts}) {
696 0 push @tags, qq{<script type="module" src="$path"></script>};
697 }
698 0 return join("\n", @tags);
699 }
700  
701 # ---------------------------------------------------------------------------
702 # Streaming SSR (Out-of-Order)
703 # ---------------------------------------------------------------------------
704  
705 0 ▶sub streaming_bootstrap ($self) {
Subroutine streaming_bootstrap: not called CC=1 SCAR=6.9
Pod undocumented
706 0 return q{<script>(function(){function s(id){var a=document.querySelector('[bf-async="'+id+'"]');var t=document.querySelector('template[bf-async-resolve="'+id+'"]');if(!a||!t)return;a.replaceChildren(t.content.cloneNode(true));a.removeAttribute('bf-async');t.remove();requestAnimationFrame(function(){if(window.__bf_hydrate)window.__bf_hydrate()})};window.__bf_swap=s})()</script>};
707 }
708  
709 0 ▶sub async_boundary ($self, $id, $fallback_html) {
Subroutine async_boundary: not called CC=1 SCAR=6.9
Pod undocumented
710 # The fallback comes in via Mojo `begin %>...<% end` capture (see
711 # MojoAdapter::renderAsync), which produces a CODE ref returning a
712 # Mojo::ByteStream. Materialize it through the backend so the rendered
713 # HTML embeds in the placeholder rather than the CODE ref's
714 # stringification.
715 0 $fallback_html = $self->backend->materialize($fallback_html);
716 0 return qq{<div bf-async="$id">$fallback_html</div>};
717 }
718  
719 0 ▶sub async_resolve ($self, $id, $content_html) {
Subroutine async_resolve: not called CC=1 SCAR=6.9
Pod undocumented
720 0 return qq{<template bf-async-resolve="$id">$content_html</template><script>__bf_swap("$id")</script>};
721 }
722  
723 # ---------------------------------------------------------------------------
724 # JS-compat callees (#1189) — invoked from generated Mojo templates as
725 # <%= bf->json($val) %>, <%= bf->floor($val) %>, etc. The MojoAdapter's
726 # `templatePrimitives` registry emits these helper calls in place of the
727 # corresponding JS callees (`JSON.stringify`, `Math.floor`, …) so the SSR
728 # template can render value-equivalent output without a JS engine.
729 #
730 # Failure policy mirrors the Go adapter (#1188): user-data marshalling
731 # (json) bubbles errors so Mojolicious aborts loudly on cycles /
732 # unsupported values rather than silently producing an empty payload.
733 # Numeric coercion follows JS semantics (NaN propagates as the special
734 # string 'NaN'; non-numeric input returns 'NaN' rather than 0). Strings
735 # always coerce to a string representation.
736 # ---------------------------------------------------------------------------
737  
738 67 ▶sub json ($self, $value) {
Subroutine json: called CC=9 SCAR=22.0
Pod undocumented
739 # `JSON.stringify`: `null` (`undef`) is "null"; `undefined` (`UNDEF`)
740 # gives no string at the top level -- the result is `UNDEF` itself,
741 # which prints nothing and omits an attribute -- an object member
742 # holding it is skipped, and an array element holding it is written as
743 # `null`.
744 #
745 # A number is written as JS writes it (`_format_number`): shortest
746 # round-trip digits, `-0` as `0`, an unpadded exponent (`-4e-8`,
747 # `-4e+21`), and NaN / Infinity as `null`, at any depth (#3787). The
748 # encoders print `%.15g` (`0.3` for `0.1 + 0.2`), pad the exponent
749 # (`-4e-08`) and spell Infinity `-Inf` or `"-Inf"`. Arrays and hashes
750 # are walked here with sorted keys, as the canonical encoders do;
751 # strings and other leaves go through the backend's encoder (Mojo's
752 # `to_json` returns a character string, suitable for embedding in HTML
753 # output via Mojo::ByteStream / `<%==`).
754 67 ▶ return $value if _undef_p($value);
Branch: 1 branch
BranchTrueFalseTotal
if _undef_p($value) 1 66 67
755 66 my $ref = ref $value;
756 66 ▶ return '[' . CORE::join(',', map { _undef_p($_) ? 'null' : $self->json($_) } @$value) . ']' if $ref eq 'ARRAY';
Branch: 2 branches
BranchTrueFalseTotal
if $ref eq "ARRAY" 14 52 66
_undef_p($_) ? : 1 37 38
757 52 ▶ if ($ref eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "HASH") 6 46 52
758 return '{' . CORE::join(',', map {
759 6 $self->backend->encode_json("$_") . ':' . $self->json($value->{$_})
760 6 } grep { !_undef_p($value->{$_}) } sort keys %$value) . '}';
761 }
762 46 ▶ if (_json_is_number($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_json_is_number($value)) 27 19 46
763 27 my $n = BarefootJS::Evaluator::_double($value + 0);
764 27 ▶ return 'null' if $n != $n || $n == 9**9**9 || $n == -(9**9**9);
Branch: 1 branch
BranchTrueFalseTotal
if $n != $n or $n == "Inf" or $n == "-Inf" 5 22 27
Condition100%6/6
$n != $n or $n == "Inf" or $n == "-Inf"
l!l&&r!l&&!r
2322
$n != $n or $n == "Inf"
l!l&&r!l&&!r
1125
MC/DC100%3/3
$n != $n or $n == "Inf" or $n == "-Inf"
$n != $n $n == "Inf" $n == "-Inf"
Truth table100%4/4
A or B or C
A= $n != $nB= $n == "Inf"C= $n == "-Inf"
ABCresult
1XX1
01X1
0011
0000
765 22 return BarefootJS::Evaluator::_format_number($n);
766 }
767 19 return $self->backend->encode_json($value);
768 }
769  
770 # Whether `json` writes $value as a JSON number. Decided from the scalar's
771 # flags the way JSON::PP / Cpanel::JSON::XS do: a scalar carrying a public
772 # string flag (SVf_POK) is a string, even after a numeric comparison has
773 # cached a number on it (`"1e5" < 0` leaves IOK/NOK set), so a JSON string
774 # prop keeps its quotes whatever the template compared it with. A number
775 # that was only stringified keeps the private flag alone (Perl 5.36+) and
776 # stays a number.
777 # `$value` as `JSON.stringify` sees it, for a host encoder: a member holding
778 # `undefined` is dropped and an `undefined` element is `null`, at any depth.
779 # The encoder (JSON::PP dies on `UNDEF`, Mojo::JSON writes `""`) never
780 # receives `UNDEF`. A JSON boolean and any other leaf pass through.
781 12 ▶sub _json_ready ($value) {
Subroutine _json_ready: called CC=5 SCAR=16.2
782 12 my $ref = ref $value;
783 12 ▶ if ($ref eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "HASH") 5 7 12
784 5 return { map { ($_ => _json_ready($value->{$_})) } grep { !_undef_p($value->{$_}) } keys %$value };
785 }
786 7 ▶ if ($ref eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "ARRAY") 2 5 7
787 2 ▶ return [ map { _undef_p($_) ? undef : _json_ready($_) } @$value ];
Branch: 1 branch
BranchTrueFalseTotal
_undef_p($_) ? : 2 0 2
788 }
789 5 ▶ return undef if _undef_p($value);
Branch: 1 branch
BranchTrueFalseTotal
if _undef_p($value) 0 5 5
790 5 return $value;
791 }
792  
793 46 ▶sub _json_is_number ($value) {
Subroutine _json_is_number: called CC=5 SCAR=16.1
794 46 ▶ return 0 if !defined $value || ref $value;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $value or ref $value 11 35 46
Condition100%3/3
not defined $value or ref $value
l!l&&r!l&&!r
4735
MC/DC100%2/2
not defined $value or ref $value
not defined $value ref $value
Truth table100%3/3
not(A) or B
A= not defined $valueB= ref $value
ABresult
1X1
011
000
795 35 my $flags = B::svref_2object(\$value)->FLAGS;
796 35 ▶ return 0 if $flags & B::SVf_POK;
Branch: 1 branch
BranchTrueFalseTotal
if $flags & 1024 8 27 35
797 27 ▶ return ($flags & (B::SVp_IOK | B::SVp_NOK)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$flags & 12288 ? : 27 0 27
798 }
799  
800 38 ▶sub string ($self, $value) {
Subroutine string: called CC=6 SCAR=18.0
Pod undocumented
801 # JS `String(v)` mirror for a display sink. `undef` (`null`) and `UNDEF`
802 # (`undefined`) render as the empty string here, as JSX renders them in a
803 # text or attribute position -- same divergence the Go adapter documents
804 # for `bf_string`. JS ToString itself is `to_string`.
805 38 ▶ return '' if _nullish($value);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($value) 6 32 38
806 # JS `Array.prototype.toString` is `this.join(',')`, applied
807 # recursively — a bare `"$value"` interpolation would otherwise
808 # stringify an ARRAY ref as its Perl memory address
809 # ("ARRAY(0x...)") instead of the JS comma-join. Reached via
810 # `.flat(0)`'s shallow copy stringified afterwards (#2262, shared
811 # with Mojolicious/Xslate via this runtime).
812 0 ▶ return CORE::join(',', map { $self->string($_) } @$value) if ref($value) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "ARRAY" 0 32 32
813 # A JSON boolean prints as JS does (`true` / `false`), not as the `1` /
814 # `0` its numeric overload yields (#3440).
815 32 ▶ return $value ? 'true' : 'false' if _is_json_bool($value);
Branch: 2 branches
BranchTrueFalseTotal
if _is_json_bool($value) 3 29 32
$value ? : 2 1 3
816 # A number prints as JS `Number::toString` does, not with Perl's `%.15g`
817 # (#3380); a string passes through unchanged.
818 29 ▶ return BarefootJS::Evaluator::_format_number($value + 0) if BarefootJS::Evaluator::_is_number($value);
Branch: 1 branch
BranchTrueFalseTotal
if BarefootJS::Evaluator::_is_number($value) 22 7 29
819 7 return "$value";
820 }
821  
822 # The text of a `<style>` / `<script>` element (`$tag`). The HTML parser
823 # decodes no character reference there, so the value is NOT HTML-escaped
824 # (`a[href="x"]` must reach the CSS parser as written); the template prints
825 # the result raw. Each `<` that could begin markup (one followed by an ASCII
826 # letter, `/`, `!` or `?`) and each `&` that could begin a character
827 # reference (one followed by an ASCII letter or `#`) is rewritten instead, in
828 # a form CSS / JS reads back as the same character: `\3c ` / `\26 ` in a
829 # `<style>`, `\u003c` / `\u0026` in a `<script>`. That leaves no end tag, no
830 # `<!--` / `<script`, no tag and no reference at all, so the text is the same
831 # both as raw text and where the element lands in foreign content (inside an
832 # `<svg>`). Mirrors `escapeRawText` in `@barefootjs/shared`.
833 #
834 # `$parts` is the element's WHOLE text as the list of its pieces (static text
835 # and each expression's value): they are joined first and encoded once,
836 # because markup can be spelled across pieces (`['<', '/style>']`).
837 0 ▶sub raw_text ($self, $tag, $parts) {
Subroutine raw_text: not called CC=4 SCAR=30.0
Pod undocumented
838 my $text = ref($parts) eq 'ARRAY'
839 0 ▶ ? CORE::join('', map { $self->string($_) } @$parts)
Branch: 1 branch
BranchTrueFalseTotal
ref $parts eq 'ARRAY' ? : 0 0 0
840 : $self->string($parts);
841 0 ▶ my %escape = $tag eq 'style'
Branch: 1 branch
BranchTrueFalseTotal
$tag eq 'style' ? : 0 0 0
842 ? ('<' => '\\3c ', '&' => '\\26 ')
843 : ('<' => '\\u003c', '&' => '\\u0026');
844 # The run of backslashes directly before the character is matched too: an
845 # odd run means the last backslash already escapes it (`"\<b"` is `<b`),
846 # so the escape replaces that pair instead of following the backslash.
847 0 $text =~ s{(?<!\\)(\\*+)(<(?=[A-Za-z/!?])|&(?=[A-Za-z\#]))}
848 0 ▶ {(length($1) % 2 ? substr($1, 1) : $1) . $escape{$2}}ge;
Branch: 1 branch
BranchTrueFalseTotal
CORE::length($1) % 2 ? : 0 0 0
849 0 return $text;
850 }
851  
852 # A JS boolean as a value the JSON encoder writes as `true` / `false`
853 # (`JSON.stringify([n, true])`): Perl holds a boolean as `1` / `''` / `0`,
854 # which encodes as a number or a string.
855 9 ▶sub boolean ($self, $value) {
Subroutine boolean: called CC=2 SCAR=6.9
Pod undocumented
856 9 ▶ return $value ? JSON::PP::true() : JSON::PP::false();
Branch: 1 branch
BranchTrueFalseTotal
$value ? : 4 5 9
857 }
858  
859 # A JSX text child's value: JSX renders nothing for a boolean (#3824 step 5).
860 # Perl holds a comparison as `1` / `''`, so only a JSON boolean is one here:
861 # the compiler materializes every boolean a displayed value can be with
862 # `boolean` first. Any other value passes through to the text sink.
863 6 ▶sub display ($self, $value) {
Subroutine display: called CC=2 SCAR=6.9
Pod undocumented
864 6 ▶ return _is_json_bool($value) ? '' : $value;
Branch: 1 branch
BranchTrueFalseTotal
_is_json_bool($value) ? : 3 3 6
865 }
866  
867 # A decoded JSON boolean (`Mojo::JSON::true` / `false`, a `JSON::PP::Boolean`).
868 38 ▶sub _is_json_bool ($value) {
Subroutine _is_json_bool: called CC=2 SCAR=7.1
869 38 my $ref = ref($value);
870 38 ▶ return $ref eq 'JSON::PP::Boolean' || $ref eq 'Mojo::JSON::_Bool';
Condition66%2/3
$ref eq 'JSON::PP::Boolean' || $ref eq 'Mojo::JSON::_Bool'
l!l&&r!l&&!r
6032
MC/DC50%1/2
$ref eq 'JSON::PP::Boolean' || $ref eq 'Mojo::JSON::_Bool'
$ref eq 'JSON::PP::Boolean' $ref eq 'Mojo::JSON::_Bool'
Truth table66%2/3
A || B
A= $ref eq 'JSON::PP::Boolean'B= $ref eq 'Mojo::JSON::_Bool'
ABresult
1X1
011
000
871 }
872  
873 7 ▶sub number ($self, $value) {
Subroutine number: called CC=3 SCAR=11.0
Pod undocumented
874 # JS `Number(v)` mirror. Numeric coerces via Perl's implicit
875 # numeric context; non-numeric / undef yield real numeric NaN
876 # (`'nan' + 0`) so downstream arithmetic propagates correctly
877 # (`Math.floor(NaN) === NaN`). Returning the literal string
878 # "NaN" would conflate the user-passing-the-string-"NaN" case
879 # with the parse-failure case, and break NaN detection in
880 # downstream helpers.
881 7 ▶ return 0 + 'nan' if _nullish($value);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($value) 3 4 7
882 4 ▶ return $value + 0 if looks_like_number($value);
Branch: 1 branch
BranchTrueFalseTotal
if &looks_like_number($value) 3 1 4
883 1 return 0 + 'nan';
884 }
885  
886 # JS `+` / `-` / `*` / `/` over numbers (#3454). The adapters emit these
887 # instead of Perl's native operators so the result is the IEEE double JS
888 # computes: a 64-bit IV sum past 2**53 rounds as a double, a perl with a
889 # wider NV (-Duselongdouble / -Dusequadmath) rounds to the double JS has,
890 # and division by zero yields +/-Infinity or NaN instead of dying. Each
891 # operand goes through JS ToNumber (`_num`): `undef` (`null`) is 0, `UNDEF`
892 # (`undefined`) NaN, a string its JS numeric value.
893 52 ▶sub _as_double { unpack('d', pack('d', $_[0])) }
Subroutine _as_double: called CC=1 SCAR=0.0
894 46 ▶sub _num { _as_double(_js_number($_[0])) }
Subroutine _num: called CC=1 SCAR=0.0
895  
896 0 ▶sub add ($self, $l, $r) {
Subroutine add: not called CC=1 SCAR=6.9
Pod undocumented
897 0 return _as_double(_num($l) + _num($r));
898 }
899  
900 2 ▶sub subtract ($self, $l, $r) {
Subroutine subtract: called CC=1 SCAR=0.0
Pod undocumented
901 2 return _as_double(_num($l) - _num($r));
902 }
903  
904 2 ▶sub multiply ($self, $l, $r) {
Subroutine multiply: called CC=1 SCAR=0.0
Pod undocumented
905 2 return _as_double(_num($l) * _num($r));
906 }
907  
908 7 ▶sub divide ($self, $l, $r) {
Subroutine divide: called CC=1 SCAR=0.0
Pod undocumented
909 7 return BarefootJS::Evaluator::_divide(_num($l), _num($r));
910 }
911  
912 # JS `%` (#3474): the truncated remainder, which takes the dividend's sign
913 # (`-7 % 2` is -1) and keeps a fraction. Perl's native `%` floors (`-7 % 2`
914 # is 1) and converts both operands to integers (`NaN % 2` is 0).
915 12 ▶sub mod ($self, $l, $r) {
Subroutine mod: called CC=1 SCAR=0.0
Pod undocumented
916 12 return BarefootJS::Evaluator::_remainder(_num($l), _num($r));
917 }
918  
919 # NaN is the only float for which `$x != $x` holds. Used as the
920 # portable sentinel check in floor/ceil/round. The `Math` helpers coerce
921 # through JS ToNumber (`null` is 0, `undefined` NaN), as `Math.floor(null)`
922 # is 0.
923 128 ▶sub _is_nan { my $n = shift; return $n != $n }
Subroutine _is_nan: called CC=1 SCAR=0.0
924  
925 # True for +/-Infinity. `9**9**9` is Perl's portable infinity literal; a
926 # finite number is always strictly less than +Inf in magnitude.
927 1 ▶sub _is_inf { my $n = shift; return $n == 9**9**9 || $n == -9**9**9 }
Subroutine _is_inf: called CC=2 SCAR=8.1
Condition33%1/3
$n == 9**9**9 || $n == -9**9**9
l!l&&r!l&&!r
001
MC/DC0%0/2
$n == 9**9**9 || $n == -9**9**9
$n == 9**9**9 $n == -9**9**9
Truth table33%1/3
A || B
A= $n == 9**9**9B= $n == -9**9**9
ABresult
1X1
011
000
928  
929 5 ▶sub floor ($self, $value) {
Subroutine floor: called CC=2 SCAR=6.9
Pod undocumented
930 5 my $n = _js_number($value);
931 5 ▶ return $n if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 2 3 5
932 3 return POSIX::floor($n);
933 }
934  
935 3 ▶sub ceil ($self, $value) {
Subroutine ceil: called CC=2 SCAR=6.9
Pod undocumented
936 3 my $n = _js_number($value);
937 3 ▶ return $n if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 1 2 3
938 2 return POSIX::ceil($n);
939 }
940  
941 5 ▶sub round ($self, $value) {
Subroutine round: called CC=2 SCAR=6.9
Pod undocumented
942 5 my $n = _js_number($value);
943 5 ▶ return $n if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 1 4 5
944 # POSIX has no `round`. JS `Math.round` rounds half toward
945 # +Infinity (so `Math.round(-1.5) === -1`, not -2). `floor(n
946 # + 0.5)` reproduces that for both signs.
947 4 return POSIX::floor($n + 0.5);
948 }
949  
950 # `Math.min(a, b)` / `Math.max(a, b)` -- two-arg forms only (#2168
951 # math-methods). JS returns NaN if either operand is NaN.
952 5 ▶sub min ($self, $a, $b) {
Subroutine min: called CC=4 SCAR=13.9
Pod undocumented
953 5 my $x = _js_number($a);
954 5 my $y = _js_number($b);
955 5 ▶ return $x if _is_nan($x);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($x) 1 4 5
956 4 ▶ return $y if _is_nan($y);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($y) 1 3 4
957 3 ▶ return $x < $y ? $x : $y;
Branch: 1 branch
BranchTrueFalseTotal
$x < $y ? : 1 2 3
958 }
959  
960 5 ▶sub max ($self, $a, $b) {
Subroutine max: called CC=4 SCAR=13.9
Pod undocumented
961 5 my $x = _js_number($a);
962 5 my $y = _js_number($b);
963 5 ▶ return $x if _is_nan($x);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($x) 1 4 5
964 4 ▶ return $y if _is_nan($y);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($y) 1 3 4
965 3 ▶ return $x > $y ? $x : $y;
Branch: 1 branch
BranchTrueFalseTotal
$x > $y ? : 2 1 3
966 }
967  
968 # `Math.abs()` (#2168 math-methods). `CORE::abs` avoids Perl's
969 # ambiguous-call warning against this package's own `abs` sub.
970 4 ▶sub abs ($self, $value) {
Subroutine abs: called CC=2 SCAR=6.9
Pod undocumented
971 4 my $n = _js_number($value);
972 4 ▶ return $n if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 1 3 4
973 3 return CORE::abs($n);
974 }
975  
976 # `date($recv, $op)` -- zero-arg `Date.prototype` method lowering (#2274,
977 # spec entry "date"). `$recv` arrives as either a `BarefootJS::Date` (this
978 # runtime's own epoch-ms wrapper, below) or an ISO-8601 string (a template
979 # prop may carry either depending on how the host populated it); both
980 # normalize to a single epoch-ms integer via `_date_epoch_ms` before
981 # dispatch. `gmtime`'s `mon` field (index 4) is ALREADY 0-based in Perl
982 # (unlike every other backend's native month accessor), so — uniquely among
983 # this catalogue's ports — `getUTCMonth` needs NO -1. `getTime` is the exact
984 # epoch-ms integer already carried by `$recv`/parsed from the string, so it
985 # needs no float rounding even for a pre-epoch instant.
986 0 ▶sub date ($self, $recv, $op) {
Subroutine date: not called CC=11 SCAR=48.8
Pod undocumented
987 0 my $ms = _date_epoch_ms($recv);
988 0 ▶ return $op eq 'toISOString' ? '' : 0 unless defined $ms;
Branch: 2 branches
BranchTrueFalseTotal
unless defined $ms 0 0 0
$op eq 'toISOString' ? : 0 0 0
989 0 ▶ return $ms if $op eq 'getTime';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getTime" 0 0 0
990  
991 # Floor (not truncate) toward -Infinity: Perl's `/` truncates toward
992 # zero, which would round a negative ms value (e.g. -14182939877) up to
993 # the wrong whole second (-14182939 instead of -14182940).
994 0 my $sec = POSIX::floor($ms / 1000);
995 0 my $msec = $ms - ($sec * 1000);
996 0 my @t = gmtime($sec); # (sec,min,hour,mday,mon,year,...) -- mon is 0-based
997  
998 0 ▶ return $t[5] + 1900 if $op eq 'getUTCFullYear';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCFullYear" 0 0 0
999 0 ▶ return $t[4] if $op eq 'getUTCMonth'; # already 0-based, no -1
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCMonth" 0 0 0
1000 0 ▶ return $t[3] if $op eq 'getUTCDate';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCDate" 0 0 0
1001 0 ▶ return $t[2] if $op eq 'getUTCHours';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCHours" 0 0 0
1002 0 ▶ return $t[1] if $op eq 'getUTCMinutes';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCMinutes" 0 0 0
1003 0 ▶ return $t[0] if $op eq 'getUTCSeconds';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "getUTCSeconds" 0 0 0
1004 0 ▶ return POSIX::strftime('%Y-%m-%dT%H:%M:%S', @t) . sprintf('.%03dZ', $msec)
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "toISOString" 0 0 0
1005 if $op eq 'toISOString';
1006 0 return 0;
1007 }
1008  
1009 # Normalizes a `date()` receiver to a single epoch-ms integer: a
1010 # `BarefootJS::Date` (unwraps `epoch_ms` directly) or an ISO-8601 string
1011 # (`YYYY-MM-DDTHH:MM:SS[.sss]Z`, the exact shape every ISO string this
1012 # runtime itself ever produces via `toISOString` above, and the shape the
1013 # golden vectors exercise). `Time::Local::timegm_modern` (core since
1014 # Time::Local 1.27, like `POSIX`) converts the broken-down UTC fields to
1015 # epoch SECONDS correctly across the full pre-1970/post-2038 range on a
1016 # 64-bit `time_t` build; unlike the legacy `timegm`, it takes `$y` as a
1017 # literal calendar year with no two-digit-year windowing heuristic — the
1018 # regex above always captures a 4-digit year, so that heuristic would only
1019 # ever be a latent footgun here, never a real branch. The optional
1020 # millisecond group defaults to 0. Returns `undef` for anything else
1021 # (unparsable string, wrong type) so `date` can apply its documented
1022 # zero-value fallback instead of dying mid-render.
1023 10 ▶sub _date_epoch_ms ($recv) {
Subroutine _date_epoch_ms: called CC=6 SCAR=18.6
1024 10 ▶ if (ref($recv) eq 'BarefootJS::Date') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $recv eq "BarefootJS::Date") 0 10 10
1025 0 return $recv->{epoch_ms};
1026 }
1027 10 ▶ return undef if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 0 10 10
1028 10 ▶ return undef unless defined $recv;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $recv 1 9 10
1029 9 ▶ return undef unless $recv =~ /\A(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?Z\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $recv =~ /\A(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{3}))?Z\z/ 1 8 9
1030 8 ▶ my ($y, $mon, $day, $h, $min, $s, $ms) = ($1, $2, $3, $4, $5, $6, $7 // 0);
Condition50%1/2
$7 // 0
l!l
80
MC/DC0%0/1
$7 // 0
$7
Truth table50%1/2
A
A= $7
Aresult
11
00
1031 8 my $epoch_s = Time::Local::timegm_modern($s, $min, $h, $day, $mon - 1, $y);
1032 8 return $epoch_s * 1000 + $ms;
1033 }
1034  
1035 # `format_date($recv, $pattern, $tz, $names)` -- pure, explicit-timezone
1036 # date formatter (#2324, #2334, spec entry "format_date"). Same receiver
1037 # contract as `date` (a `BarefootJS::Date`, an ISO-8601 string, or
1038 # undef/unparseable -> ''), then pure pattern substitution over the
1039 # shifted instant. Mirrors packages/client/src/format-date.ts
1040 # byte-for-byte -- deterministic, no locale, no host TZ, no `time()`.
1041 #
1042 # `$tz` (#2344) is 'UTC', a range-valid fixed offset `±HH:MM` (hours
1043 # 00-23, minutes 00-59), or a canonical IANA zone name ('Asia/Tokyo')
1044 # resolved through tzdata via DateTime::TimeZone -- the zone's UTC
1045 # offset AT THE INSTANT being formatted (DST-aware,
1046 # historical-transition-aware, seconds precision: pre-standard LMT
1047 # offsets like Tokyo's +09:18:59 count). Anything unresolvable -- an
1048 # unknown zone, a malformed or out-of-range offset ('+9:00', '+25:00'
1049 # fall through to the zone lookup), DateTime::TimeZone's implicit
1050 # 'local'/'floating' specials -- DIES, aborting the render loudly: the
1051 # JS reference throws a RangeError there, and a silently substituted
1052 # timezone is the one failure mode this helper must not have (the
1053 # pre-#2344 normalize-to-UTC total function is gone). The receiver
1054 # contract still precedes tz validation (undef/unparseable -> '').
1055 #
1056 # The shifted instant's UTC calendar fields come from the same
1057 # floor-toward-negative-infinity + `gmtime` discipline as `date` above
1058 # (Perl's `/` truncates toward zero, which mis-floors negative ms), and
1059 # `gmtime`'s 0-based `mon` needs +1 here (unlike `getUTCMonth` in `date`,
1060 # because the pattern token `M`/`MM` is the 1-based JS `Date` display
1061 # month, not the raw accessor value). `gmtime`'s `wday` (element 6) is
1062 # already 0-based Sunday-first, matching JS `getUTCDay()` and the
1063 # `$names` table's weekday section layout -- both read off the same
1064 # offset-shifted `gmtime` call, so pre-1970 instants get the identical
1065 # floor-division-derived weekday as the numeric tokens.
1066 #
1067 # `$names` (#2334) is an arrayref of strings in fixed flat layout:
1068 # [0..11] wide months, [12..23] abbreviated months, [24..30] wide
1069 # weekdays (Sunday-first), [31..37] abbreviated weekdays. A name token
1070 # indexing a missing entry, or given an undef/short/absent table, renders
1071 # '' (defined-or guard) -- never dies.
1072 #
1073 # Token substitution mirrors the JS reference exactly: `s///ge` over the
1074 # `YYYY|MMMM|MMM|MM|DD|dddd|ddd|M|D` alternation (longest-match order so
1075 # e.g. `MMMM` binds before `MMM`/`MM`/`M`, `dddd` before `ddd`), any other
1076 # character (including multi-byte literals) passes through untouched.
1077 # `YYYY` is `abs(year)` zero-padded to (at least) 4 digits, `-`-prefixed
1078 # when the year is negative; `MM`/`DD` zero-pad to 2; `M`/`D` are bare.
1079 10 ▶sub format_date ($self, $recv, $pattern, $tz, $names = []) {
Subroutine format_date: called CC=15 SCAR=32.1
Pod undocumented
1080 10 my $ms = _date_epoch_ms($recv);
1081 10 ▶ return '' unless defined $ms;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ms 2 8 10
1082  
1083 8 my $offset_seconds = 0;
1084 8 ▶ if ($tz ne 'UTC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tz ne "UTC") 8 0 8
1085 8 ▶ if ($tz =~ /^([+-])([01][0-9]|2[0-3]):([0-5][0-9])$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($tz =~ /^([+-])([01][0-9]|2[0-3]):([0-5][0-9])$/) { } 0 8 8
1086 0 ▶ $offset_seconds = ($1 eq '-' ? -1 : 1) * ($2 * 3600 + $3 * 60);
Branch: 1 branch
BranchTrueFalseTotal
$1 eq '-' ? : 0 0 0
1087 }
1088 else {
1089 8 $offset_seconds = _format_date_zone_offset($tz, $ms);
1090 }
1091 }
1092  
1093 1 my $shifted = $ms + $offset_seconds * 1000;
1094 1 my $sec = POSIX::floor($shifted / 1000);
1095 1 my @t = gmtime($sec); # (sec,min,hour,mday,mon,year,wday,...) -- mon/wday are 0-based
1096  
1097 1 my $year = $t[5] + 1900;
1098 1 my $month = $t[4] + 1; # 1-based JS display month, unlike getUTCMonth in `date`
1099 1 my $day = $t[3];
1100 1 my $weekday = $t[6]; # 0 = Sunday, matching the $names table's Sunday-first layout
1101 1 ▶ my $yyyy = ($year < 0 ? '-' : '') . sprintf('%04d', CORE::abs($year));
Branch: 1 branch
BranchTrueFalseTotal
$year < 0 ? : 0 1 1
1102 1 my $mm = sprintf('%02d', $month);
1103 1 my $dd = sprintf('%02d', $day);
1104 0 ▶ my $name_at = sub ($index) { $names->[$index] // '' };
Subroutine __ANON__: not called CC=2 SCAR=13.0
Condition0%0/2
$names->[$index] // ""
l!l
00
MC/DC0%0/1
$names->[$index] // ""
$names->[$index]
Truth table0%0/2
A
A= $names->[$index]
Aresult
11
00
1105  
1106 1 (my $out = $pattern) =~ s/YYYY|MMMM|MMM|MM|DD|dddd|ddd|M|D/
1107 3 ▶ $& eq 'YYYY' ? $yyyy
Branch: 8 branches
BranchTrueFalseTotal
$& eq 'YYYY' ? : 1 2 3
$& eq 'MMMM' ? : 0 2 2
$& eq 'MMM' ? : 0 2 2
$& eq 'MM' ? : 1 1 2
$& eq 'DD' ? : 1 0 1
$& eq 'dddd' ? : 0 0 0
$& eq 'ddd' ? : 0 0 0
$& eq 'M' ? : 0 0 0
1108 : $& eq 'MMMM' ? $name_at->($month - 1)
1109 : $& eq 'MMM' ? $name_at->(12 + $month - 1)
1110 : $& eq 'MM' ? $mm
1111 : $& eq 'DD' ? $dd
1112 : $& eq 'dddd' ? $name_at->(24 + $weekday)
1113 : $& eq 'ddd' ? $name_at->(31 + $weekday)
1114 : $& eq 'M' ? $month
1115 : $day
1116 /gex;
1117 1 return $out;
1118 }
1119  
1120 # Minimal `utc_rd_values`/`utc_year` provider so
1121 # `DateTime::TimeZone->offset_for_datetime` can resolve an offset for a raw
1122 # epoch instant without pulling the full DateTime object model into this
1123 # runtime (its documented duck-type contract is exactly these two methods).
1124 # RD day 719163 is 1970-01-01; the floor-division discipline matches
1125 # `format_date`'s own pre-1970 handling.
1126 17 package BarefootJS::_TZProbe {
1127  
1128 1 ▶ sub new ($class, $epoch_s) {
Subroutine new: called CC=1 SCAR=0.0
1129 1 my $days = POSIX::floor($epoch_s / 86400);
1130 1 my @t = gmtime($epoch_s);
1131 1 return bless {
1132 rd_days => $days + 719_163,
1133 rd_secs => $epoch_s - $days * 86400,
1134 year => $t[5] + 1900,
1135 }, $class;
1136 }
1137  
1138 0 ▶ sub utc_rd_values ($self) { return ($self->{rd_days}, $self->{rd_secs}, 0) }
Subroutine utc_rd_values: not called CC=1 SCAR=6.9
1139 0 ▶ sub utc_year ($self) { return $self->{year} }
Subroutine utc_year: not called CC=1 SCAR=6.9
1140  
1141 1 ▶ sub utc_rd_as_seconds ($self) {
Subroutine utc_rd_as_seconds: called CC=1 SCAR=0.0
1142 1 return $self->{rd_days} * 86400 + $self->{rd_secs};
1143 }
1144 }
1145  
1146 # Resolve a canonical IANA zone name's UTC offset (whole seconds) at the
1147 # epoch-ms instant through DateTime::TimeZone (#2344). Loaded lazily so the
1148 # 'UTC'/fixed-offset paths -- and every other helper -- keep working on a
1149 # core-modules-only install; reaching a named zone without the module dies
1150 # with the same loud message as an unknown zone (never a silent UTC
1151 # fallback). 'local' and 'floating' are DateTime::TimeZone specials that
1152 # would read the host environment / return a zoneless offset -- both
1153 # refused explicitly, same as the JS reference refuses 'Local'.
1154 8 ▶sub _format_date_zone_offset ($tz, $ms) {
Subroutine _format_date_zone_offset: called CC=6 SCAR=17.9
1155 8 ▶ if ($tz eq '' || lc($tz) eq 'local' || lc($tz) eq 'floating') {
Branch: 1 branch
BranchTrueFalseTotal
if ($tz eq "" or CORE::lc $tz eq "local" or CORE::lc $tz eq "floating") 4 4 8
Condition100%6/6
$tz eq "" or CORE::lc $tz eq "local" or CORE::lc $tz eq "floating"
l!l&&r!l&&!r
314
$tz eq "" or CORE::lc $tz eq "local"
l!l&&r!l&&!r
125
MC/DC100%3/3
$tz eq "" or CORE::lc $tz eq "local" or CORE::lc $tz eq "floating"
$tz eq "" CORE::lc $tz eq "local" CORE::lc $tz eq "floating"
Truth table100%4/4
A or B or C
A= $tz eq ""B= CORE::lc $tz eq "local"C= CORE::lc $tz eq "floating"
ABCresult
1XX1
01X1
0011
0000
1156 4 die qq{format_date: unresolvable timeZone "$tz"};
1157 }
1158 4 my $zone = eval {
1159 4 require DateTime::TimeZone;
1160 4 DateTime::TimeZone->new(name => $tz);
1161 };
1162 4 ▶ if (!$zone) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($zone) 3 1 4
1163 # Carry the underlying loader/constructor error: "unresolvable"
1164 # covers both an unknown zone AND a broken/absent DateTime::TimeZone
1165 # installation, and the two need different fixes.
1166 3 ▶ my $cause = $@ ? " ($@)" : '';
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 3 0 3
1167 3 die qq{format_date: unresolvable timeZone "$tz"$cause};
1168 }
1169 1 return $zone->offset_for_datetime(
1170 BarefootJS::_TZProbe->new(POSIX::floor($ms / 1000)));
1171 }
1172  
1173 # ---------------------------------------------------------------------------
1174 # Array / String method helpers (#1448 Tier A)
1175 # ---------------------------------------------------------------------------
1176 #
1177 # `Array.prototype.includes(x)` and `String.prototype.includes(sub)`
1178 # share a method name in JS; the JSX parser can't tell the two
1179 # receiver shapes apart without TS type inference, so both lower to
1180 # the same IR node (`array-method` / method `includes`). This helper
1181 # dispatches at the Perl level via `ref()`:
1182 # - ARRAY ref: scan elements with `BarefootJS::Evaluator::_same_value_zero`,
1183 # matching `Array.prototype.includes`'s SameValueZero
1184 # semantics (no cross-type coercion, e.g. `[2].includes("2")`
1185 # is false; NaN matches NaN) — the same algorithm the
1186 # evaluator's serialized-callback path already uses for
1187 # `.includes`, so both positions agree. This used to be a
1188 # stringy `eq` scan, which coerced numbers to strings
1189 # (`[2].includes("2")` was true) and diverged from JS.
1190 # - scalar: `index($recv, $sub) != -1`, the needle JS ToString'd
1191 # (`null` searches for "null", `undefined` for
1192 # "undefined").
1193 # Anything else (HASH ref, code ref) returns false — matches the
1194 # JS semantic where `.includes` is only defined on Array /
1195 # TypedArray / String.
1196  
1197 # JS `a === b` when neither operand's type is known at compile time. Perl's
1198 # numeric `==` reads two different non-numeric strings as `0 == 0`, and `eq`
1199 # reads `1` and `1.0` as different, so the comparison goes by the operands'
1200 # JS types: numbers by value, strings by content, booleans by truth value,
1201 # `undef` (`null`) only to `undef`, `UNDEF` (`undefined`) only to `UNDEF`, an
1202 # object or array only to the same reference,
1203 # and values of different types never equal. The
1204 # result is a Perl boolean, the same value the native operators yield.
1205 26 ▶sub strict_eq ($self, $l, $r) {
Subroutine strict_eq: called CC=2 SCAR=6.9
Pod undocumented
1206 26 ▶ return BarefootJS::Evaluator::_strict_eq($l, $r) ? !!1 : !!0;
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_strict_eq($l, $r) ? : 9 17 26
1207 }
1208  
1209 # JS primitive helpers (spec/js-primitive-semantics.md, "Operation table"):
1210 # ToBoolean, ToNumber, ToString, the relational operators, binary `+` and
1211 # unary `-`. Each delegates to the callback evaluator's primitive of the same
1212 # operation, so a template helper call and a callback body share one
1213 # implementation. A boolean result is a Perl boolean, as `strict_eq`'s is.
1214 # Unlike `number` and `string` (display helpers: `undef` / `UNDEF` -> NaN /
1215 # ''), an `undef` operand reads as JS null here (0 / 'null') and `UNDEF` as JS
1216 # undefined (NaN / 'undefined').
1217 1 ▶sub truthy ($self, $v) {
Subroutine truthy: called CC=2 SCAR=7.6
Pod undocumented
1218 1 ▶ return BarefootJS::Evaluator::_truthy($v) ? !!1 : !!0;
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_truthy($v) ? : 0 1 1
1219 }
1220  
1221 # Boxes for a value-position JS `l || r` / `l && r` (#3824): the adapters
1222 # spell `l || r` as `(keep_truthy(l) || [r])->[0]` and `l && r` as
1223 # `(keep_falsy(l) || [r])->[0]`. `keep_truthy` is the one-element arrayref
1224 # `[$v]` when `$v` is JS-truthy and undef otherwise (`keep_falsy` the
1225 # reverse), so Perl's `||` stops at `$v`'s box exactly when JS returns `$v`
1226 # itself and builds `[r]` only otherwise (the short circuit); `->[0]` unboxes
1227 # the operand. Each operand appears once, so a chain grows linearly.
1228 0 ▶sub keep_truthy ($self, $v) {
Subroutine keep_truthy: not called CC=2 SCAR=17.9
Pod undocumented
1229 0 ▶ return BarefootJS::Evaluator::_truthy($v) ? [$v] : undef;
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_truthy($v) ? : 0 0 0
1230 }
1231  
1232 0 ▶sub keep_falsy ($self, $v) {
Subroutine keep_falsy: not called CC=2 SCAR=17.9
Pod undocumented
1233 0 ▶ return BarefootJS::Evaluator::_truthy($v) ? undef : [$v];
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_truthy($v) ? : 0 0 0
1234 }
1235  
1236 # The box for a value-position JS `l ?? r`: the adapters spell it as
1237 # `(keep_nonnil(l) || [r])->[0]`, so each operand appears once. Only the two
1238 # nils (`null`, `undefined`) are absent; `0`, `''` and `false` are kept, as
1239 # in JS. Perl's `//` would keep `UNDEF`.
1240 4 ▶sub keep_nonnil ($self, $v) {
Subroutine keep_nonnil: called CC=2 SCAR=6.9
Pod undocumented
1241 4 ▶ return _nullish($v) ? undef : [$v];
Branch: 1 branch
BranchTrueFalseTotal
_nullish($v) ? : 2 2 4
1242 }
1243  
1244 2 ▶sub to_number ($self, $v) { return BarefootJS::Evaluator::_to_number($v) }
Subroutine to_number: called CC=1 SCAR=0.0
Pod undocumented
1245  
1246 2 ▶sub to_string ($self, $v) { return BarefootJS::Evaluator::_to_string($v) }
Subroutine to_string: called CC=1 SCAR=0.0
Pod undocumented
1247  
1248 2 ▶sub plus ($self, $l, $r) { return BarefootJS::Evaluator::_binary('+', $l, $r) }
Subroutine plus: called CC=1 SCAR=0.0
Pod undocumented
1249  
1250 0 ▶sub neg ($self, $v) { return BarefootJS::Evaluator::_unary('-', $v) }
Subroutine neg: not called CC=1 SCAR=6.9
Pod undocumented
1251  
1252 1 ▶sub lt ($self, $l, $r) { return BarefootJS::Evaluator::_relational('<', $l, $r) ? !!1 : !!0 }
Subroutine lt: called CC=2 SCAR=7.6
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_relational('<', $l, $r) ? : 0 1 1
1253 1 ▶sub le ($self, $l, $r) { return BarefootJS::Evaluator::_relational('<=', $l, $r) ? !!1 : !!0 }
Subroutine le: called CC=2 SCAR=7.6
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_relational('<=', $l, $r) ? : 1 0 1
1254 0 ▶sub gt ($self, $l, $r) { return BarefootJS::Evaluator::_relational('>', $l, $r) ? !!1 : !!0 }
Subroutine gt: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_relational('>', $l, $r) ? : 0 0 0
1255 0 ▶sub ge ($self, $l, $r) { return BarefootJS::Evaluator::_relational('>=', $l, $r) ? !!1 : !!0 }
Subroutine ge: not called CC=2 SCAR=17.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
BarefootJS::Evaluator::_relational('>=', $l, $r) ? : 0 0 0
1256  
1257 22 ▶sub includes ($self, $recv, $elem) {
Subroutine includes: called CC=6 SCAR=17.9
Pod undocumented
1258 22 ▶ if (ref($recv) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $recv eq "ARRAY") 13 9 22
1259 13 for my $item (@$recv) {
1260 18 ▶ return 1 if BarefootJS::Evaluator::_same_value_zero($item, $elem);
Branch: 1 branch
BranchTrueFalseTotal
if BarefootJS::Evaluator::_same_value_zero($item, $elem) 7 11 18
1261 }
1262 6 return 0;
1263 }
1264 9 ▶ return 0 if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 2 7 9
1265 # The needle is JS ToString'd (`"anullb".includes(null)` is true).
1266 7 ▶ return index($self->string($recv), _js_string($elem)) != -1 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
index($self->string($recv), _js_string($elem)) != -1 ? : 4 3 7
1267 }
1268  
1269 # `Array.prototype.filter(fn)` / `.every(fn)` / `.some(fn)`. The Xslate adapter
1270 # lowers a JS arrow predicate to a Kolon lambda (`-> $x { ... }`), which is
1271 # callable from Perl as a code ref, and emits `$bf.filter($arr, <lambda>)`.
1272 # `filter` returns a new arrayref; `every` / `some` return 1/0. Non-array /
1273 # empty receivers follow JS (`filter` → [], `every` → true, `some` → false).
1274 # (The Mojo adapter lowers these shapes inline and never reaches these methods.)
1275 0 ▶sub filter ($self, $recv, $pred) {
Subroutine filter: not called CC=2 SCAR=17.9
Pod undocumented
1276 0 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1277 0 return [ grep { $pred->($_) } @$recv ];
1278 }
1279  
1280 0 ▶sub every ($self, $recv, $pred) {
Subroutine every: not called CC=4 SCAR=30.0
Pod undocumented
1281 0 ▶ return 1 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1282 0 ▶ for my $item (@$recv) { return 0 unless $pred->($item) }
Branch: 1 branch
BranchTrueFalseTotal
unless &$pred($item) 0 0 0
1283 0 return 1;
1284 }
1285  
1286 0 ▶sub some ($self, $recv, $pred) {
Subroutine some: not called CC=4 SCAR=30.0
Pod undocumented
1287 0 ▶ return 0 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1288 0 ▶ for my $item (@$recv) { return 1 if $pred->($item) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($item) 0 0 0
1289 0 return 0;
1290 }
1291  
1292 # `Array.prototype.find(fn)` / `.findIndex(fn)` / `.findLast(fn)` /
1293 # `.findLastIndex(fn)` — same Kolon-lambda predicate mechanism as filter. The
1294 # camelCase JS names lower to these snake_case methods (like index_of /
1295 # last_index_of). `find` / `find_last` return the matching element (or JS
1296 # `undefined`, `UNDEF`); the index forms return the 0-based position (or -1).
1297 1 ▶sub find ($self, $recv, $pred) {
Subroutine find: called CC=4 SCAR=14.5
Pod undocumented
1298 1 ▶ return $UNDEF unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 1 1
1299 1 ▶ for my $item (@$recv) { return $item if $pred->($item) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($item) 0 1 1
1300 1 return $UNDEF;
1301 }
1302  
1303 0 ▶sub find_index ($self, $recv, $pred) {
Subroutine find_index: not called CC=4 SCAR=30.0
Pod undocumented
1304 0 ▶ return -1 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1305 0 ▶ for my $i (0 .. $#$recv) { return $i if $pred->($recv->[$i]) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($recv->[$i]) 0 0 0
1306 0 return -1;
1307 }
1308  
1309 1 ▶sub find_last ($self, $recv, $pred) {
Subroutine find_last: called CC=4 SCAR=14.5
Pod undocumented
1310 1 ▶ return $UNDEF unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 1 1
1311 1 ▶ for my $i (reverse 0 .. $#$recv) { return $recv->[$i] if $pred->($recv->[$i]) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($recv->[$i]) 0 1 1
1312 1 return $UNDEF;
1313 }
1314  
1315 0 ▶sub find_last_index ($self, $recv, $pred) {
Subroutine find_last_index: not called CC=4 SCAR=30.0
Pod undocumented
1316 0 ▶ return -1 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1317 0 ▶ for my $i (reverse 0 .. $#$recv) { return $i if $pred->($recv->[$i]) }
Branch: 1 branch
BranchTrueFalseTotal
if &$pred($recv->[$i]) 0 0 0
1318 0 return -1;
1319 }
1320  
1321 # `String.prototype.toLowerCase()` / `.toUpperCase()`. Kolon has a builtin
1322 # `.join` array method (so the adapter uses that directly) but no builtin
1323 # `lc` / `uc`, so these live on the runtime object. `CORE::` avoids recursing
1324 # into these methods.
1325 0 ▶sub lc ($self, $s) { return CORE::lc($self->string($s)) }
Subroutine lc: not called CC=1 SCAR=6.9
Pod undocumented
1326 0 ▶sub uc ($self, $s) { return CORE::uc($self->string($s)) }
Subroutine uc: not called CC=1 SCAR=6.9
Pod undocumented
1327  
1328 # `Array.prototype.join(sep)` with JS semantics: an omitted or `undefined`
1329 # separator is ",", any other one is ToString'd (`null` joins with "null");
1330 # undefined / null elements render as empty (`[1,,2].join(",")` → "1,,2").
1331 # Kolon has a builtin `.join`, but routing through the runtime keeps the
1332 # JS-compat element handling in one place. `CORE::join` avoids recursing.
1333 3 ▶sub join ($self, $recv, $sep = $OMITTED) {
Subroutine join: called CC=4 SCAR=13.9
Pod undocumented
1334 3 ▶ return '' unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 3 3
1335 3 ▶ $sep = _omitted($sep) ? ',' : _js_string($sep);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($sep) ? : 2 1 3
1336 # Each element routes through `string()` (JS `String(v)`), not a bare
1337 # defined-check, so a nested-array element (e.g. `.flat(0)`'s shallow
1338 # copy, #2262) gets the recursive JS comma-join instead of stringifying
1339 # to a Perl ARRAY ref's memory address.
1340 3 return CORE::join($sep, map { $self->string($_) } @$recv);
1341 }
1342  
1343 # `.length` — JS works on BOTH arrays (element count) and strings; Kolon's
1344 # builtin `.size()` is array-only and faults on a string. So dispatch on ref
1345 # type here. The string branch counts UTF-16 CODE UNITS, matching JS
1346 # `String.prototype.length` (#2255) — NOT `CORE::length`'s Unicode codepoint
1347 # count. A codepoint outside the Basic Multilingual Plane (astral,
1348 # U+10000-U+10FFFF — e.g. '👍') is a surrogate PAIR in UTF-16, so it counts
1349 # as 2, not 1; '日本語' is 3 either way (BMP-only). An object's `.length` is
1350 # its own `length` property (`{ length: 3 }`), `undefined` when it has none — the
1351 # same read the evaluator's `_read_index` does (`UNDEF` when it has none).
1352 1 ▶sub length ($self, $recv) {
Subroutine length: called CC=8 SCAR=36.8
Pod undocumented
1353 1 ▶ return scalar @$recv if ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv eq "ARRAY" 0 1 1
1354 1 ▶ return BarefootJS::Evaluator::_read_index($recv, 'length') if ref($recv) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv eq "HASH" 1 0 1
1355 0 ▶ return 0 if ref($recv) || _nullish($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv or _nullish($recv) 0 0 0
Condition0%0/3
ref $recv or _nullish($recv)
l!l&&r!l&&!r
000
MC/DC0%0/2
ref $recv or _nullish($recv)
ref $recv _nullish($recv)
Truth table0%0/3
A or B
A= ref $recvB= _nullish($recv)
ABresult
1X1
011
000
1356 0 my $n = 0;
1357 0 ▶ $n += ord($_) > 0xFFFF ? 2 : 1 for split //, ($recv // '');
Branch: 1 branch
BranchTrueFalseTotal
ord $_ > 65535 ? : 0 0 0
Condition0%0/2
$recv // ""
l!l
00
MC/DC0%0/1
$recv // ""
$recv
Truth table0%0/2
A
A= $recv
Aresult
11
00
1358 0 return $n;
1359 }
1360  
1361 # `arr[index]` / `hash[key]` — a runtime-polymorphic dynamic-key element
1362 # access (`emitIndexAccessPerl`, expr/operand.ts). Perl's deref syntax
1363 # forces a compile-time choice between `->{$k}` (hash) and `->[$k]`
1364 # (array), but a dynamic key's shape is only known at run time (#2491), so
1365 # this dispatches on the receiver's RUNTIME `ref`. It is the callback
1366 # evaluator's `_read_index`, so a template read and a callback read share
1367 # one JS ToPropertyKey implementation (spec/js-primitive-semantics.md,
1368 # "ToPropertyKey and index read").
1369 30 ▶sub get ($self, $collection, $key) {
Subroutine get: called CC=1 SCAR=0.0
Pod undocumented
1370 30 return BarefootJS::Evaluator::_read_index($collection, $key);
1371 }
1372  
1373 # JS `o?.k`: `undefined` over a nullish receiver, the read of `k` (`get`)
1374 # otherwise.
1375 5 ▶sub get_opt ($self, $collection, $key) {
Subroutine get_opt: called CC=2 SCAR=6.9
Pod undocumented
1376 5 ▶ return $UNDEF if _nullish($collection);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($collection) 2 3 5
1377 3 return BarefootJS::Evaluator::_read_index($collection, $key);
1378 }
1379  
1380 # JS `undefined` as a template spells it (`bf->undefined` / `$bf.undefined()`):
1381 # the `undefined` identifier, an omitted method argument's default, the
1382 # result of a `?.` over a nullish receiver.
1383 1 ▶sub undefined ($self) { return $UNDEF }
Subroutine undefined: called CC=1 SCAR=0.0
Pod undocumented
1384  
1385 # The nil tests (spec/js-undefined-value.md, decisions 3 and 7): JS
1386 # `x === undefined`, `x === null` and the loose `x == null`. A template
1387 # spells a nil-test plan, an attribute omission and a `??` through them;
1388 # Perl's `defined` / `//` see `UNDEF` as a value. A boolean result is a Perl
1389 # boolean, as `strict_eq`'s is.
1390 2 ▶sub is_undefined ($self, $v) { return _undef_p($v) ? !!1 : !!0 }
Subroutine is_undefined: called CC=2 SCAR=6.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
_undef_p($v) ? : 1 1 2
1391 2 ▶sub is_null ($self, $v) { return defined($v) ? !!0 : !!1 }
Subroutine is_null: called CC=2 SCAR=6.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 1 1 2
1392 3 ▶sub is_nullish ($self, $v) { return _nullish($v) ? !!1 : !!0 }
Subroutine is_nullish: called CC=2 SCAR=6.9
Pod undocumented
Branch: 1 branch
BranchTrueFalseTotal
_nullish($v) ? : 2 1 3
1393  
1394 # `isValidElement(x)` -- the framework "is this a renderable element (not
1395 # plain text)?" predicate `Slot`'s `asChild` pattern uses (#2266). Mirrors
1396 # JS's `'tag' in x && 'props' in x`: true only for a HASH ref carrying both
1397 # keys (case-insensitively, matching the case-tolerant field lookups
1398 # elsewhere in this module). A passed-through JSX child is represented as
1399 # pre-rendered markup (a plain string) on this SSR model, so a non-empty
1400 # STRING child is NOT a valid element -- routing `isValidElement` through
1401 # bare truthiness here would wrongly take the element-merge branch.
1402 0 ▶sub is_element ($self, $v) {
Subroutine is_element: not called CC=7 SCAR=40.3
Pod undocumented
1403 0 ▶ return 0 unless ref($v) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $v eq "HASH" 0 0 0
1404 0 my ($has_tag, $has_props) = (0, 0);
1405 0 for my $key (keys %$v) {
1406 0 ▶ $has_tag = 1 if CORE::lc($key) eq 'tag';
Branch: 1 branch
BranchTrueFalseTotal
if CORE::lc $key eq "tag" 0 0 0
1407 0 ▶ $has_props = 1 if CORE::lc($key) eq 'props';
Branch: 1 branch
BranchTrueFalseTotal
if CORE::lc $key eq "props" 0 0 0
1408 }
1409 0 ▶ return ($has_tag && $has_props) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$has_tag && $has_props ? : 0 0 0
Condition0%0/3
$has_tag and $has_props
!ll&&!rl&&r
000
MC/DC0%0/2
$has_tag and $has_props
$has_tag $has_props
Truth table0%0/3
A and B
A= $has_tagB= $has_props
ABresult
0X0
100
111
1410 }
1411  
1412 # `Array.prototype.indexOf(x)` / `Array.prototype.lastIndexOf(x)`
1413 # value-equality search (#1448 Tier A). Returns the 0-based position
1414 # of the first / last matching element, or -1 if not found.
1415 # A plain-scalar (string) receiver is `String.prototype.indexOf` /
1416 # `.lastIndexOf` instead, counted in UTF-16 code units like JS (#3613):
1417 # `'日本語'.indexOf('本')` is 1 and `'a😀b'.indexOf('b')` is 3. Any other
1418 # reference returns -1 (`.indexOf` is only defined on Array / TypedArray /
1419 # String).
1420  
1421 14 ▶sub _array_index_of ($recv, $elem, $reverse) {
Subroutine _array_index_of: called CC=11 SCAR=24.0
1422 14 ▶ return -1 unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 1 13 14
1423 13 ▶ my @indices = $reverse ? (reverse 0 .. $#{$recv}) : (0 .. $#{$recv});
Branch: 1 branch
BranchTrueFalseTotal
$reverse ? : 5 8 13
1424 13 for my $i (@indices) {
1425 31 my $item = $recv->[$i];
1426 # Strict equality tells the nils apart: `null` matches only `null`,
1427 # `undefined` only `undefined`.
1428 31 ▶ if (_nullish($item) || _nullish($elem)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_nullish($item) or _nullish($elem)) 6 25 31
Condition66%2/3
_nullish($item) or _nullish($elem)
l!l&&r!l&&!r
6025
MC/DC50%1/2
_nullish($item) or _nullish($elem)
_nullish($item) _nullish($elem)
Truth table66%2/3
A or B
A= _nullish($item)B= _nullish($elem)
ABresult
1X1
011
000
1429 6 ▶ return $i if (!defined $item && !defined $elem) || (_undef_p($item) && _undef_p($elem));
Branch: 1 branch
BranchTrueFalseTotal
if not defined $item || defined $elem or _undef_p($item) and _undef_p($elem) 4 2 6
Condition100%9/9
not defined $item || defined $elem or _undef_p($item) and _undef_p($elem)
l!l&&r!l&&!r
312
defined $item || defined $elem
l!l&&r!l&&!r
213
_undef_p($item) and _undef_p($elem)
!ll&&!rl&&r
111
MC/DC75%3/4
not defined $item || defined $elem or _undef_p($item) and _undef_p($elem)
defined $item defined $elem _undef_p($item) _undef_p($elem)
Truth table57%4/7
not(A || B) or C and D
A= defined $itemB= defined $elemC= _undef_p($item)D= _undef_p($elem)
ABCDresult
00XX1
1X111
01111
1X0X0
1X100
010X0
01100
1430 2 next;
1431 }
1432 25 ▶ return $i if $item eq $elem;
Branch: 1 branch
BranchTrueFalseTotal
if $item eq $elem 5 20 25
1433 }
1434 4 return -1;
1435 }
1436  
1437 # JS `ToIntegerOrInfinity` for a string position or index (#3613): NaN →
1438 # 0, truncation toward zero, and ±Infinity clamped to ±2**53 so the
1439 # caller's range check treats it as out of range (a bare `int()` keeps
1440 # NaN, which then indexes element 0 with a warning).
1441 92 ▶sub _to_integer_or_infinity ($self, $value) {
Subroutine _to_integer_or_infinity: called CC=4 SCAR=13.9
1442 92 my $n = _js_number($value);
1443 92 ▶ return 0 if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 6 86 92
1444 86 ▶ return 2**53 if $n >= 2**53;
Branch: 1 branch
BranchTrueFalseTotal
if $n >= "9.00719925474099e+15" 3 83 86
1445 83 ▶ return -(2**53) if $n <= -(2**53);
Branch: 1 branch
BranchTrueFalseTotal
if $n <= "-9.00719925474099e+15" 1 82 83
1446 82 return int($n);
1447 }
1448  
1449 # `$s` as JS sees it: a list of UTF-16 code units. JS string positions
1450 # (`indexOf`, `at`, `startsWith`'s position, …) count these, so an astral
1451 # character such as '😀' is two units (#3613).
1452 70 ▶sub _utf16_units ($s) {
Subroutine _utf16_units: called CC=3 SCAR=11.0
1453 70 my @units;
1454 70 for my $o (map { ord } split //, $s) {
1455 154 ▶ if ($o > 0xFFFF) {
Branch: 1 branch
BranchTrueFalseTotal
if ($o > 65535) { } 12 142 154
1456 12 $o -= 0x10000;
1457 12 push @units, 0xD800 + ($o >> 10), 0xDC00 + ($o & 0x3FF);
1458 } else {
1459 142 push @units, $o;
1460 }
1461 }
1462 70 return \@units;
1463 }
1464  
1465 # Whether `$needle` (unit list) occurs in `$hay` at unit offset `$at`.
1466 36 ▶sub _utf16_has_at ($hay, $needle, $at) {
Subroutine _utf16_has_at: called CC=5 SCAR=16.1
1467 36 ▶ return 0 if $at < 0 || $at + @$needle > @$hay;
Branch: 1 branch
BranchTrueFalseTotal
if $at < 0 or $at + @$needle > @$hay 3 33 36
Condition100%3/3
$at < 0 or $at + @$needle > @$hay
l!l&&r!l&&!r
2133
MC/DC100%2/2
$at < 0 or $at + @$needle > @$hay
$at < 0 $at + @$needle > @$hay
Truth table100%3/3
A or B
A= $at < 0B= $at + @$needle > @$hay
ABresult
1X1
011
000
1468 33 for my $i (0 .. $#$needle) {
1469 34 ▶ return 0 if $hay->[$at + $i] != $needle->[$i];
Branch: 1 branch
BranchTrueFalseTotal
if $$hay[$at + $i] != $needle->[$i] 13 21 34
1470 }
1471 20 return 1;
1472 }
1473  
1474 10 ▶sub _utf16_index_of ($self, $recv, $elem, $reverse) {
Subroutine _utf16_index_of: called CC=4 SCAR=13.9
1475 10 my $hay = _utf16_units("$recv");
1476 # The needle is JS ToString'd (`'anullb'.indexOf(null)` is 1).
1477 10 my $needle = _utf16_units(_js_string($elem));
1478 10 my $last = @$hay - @$needle;
1479 10 ▶ my @indices = $reverse ? (reverse 0 .. $last) : (0 .. $last);
Branch: 1 branch
BranchTrueFalseTotal
$reverse ? : 4 6 10
1480 10 for my $i (@indices) {
1481 17 ▶ return $i if _utf16_has_at($hay, $needle, $i);
Branch: 1 branch
BranchTrueFalseTotal
if _utf16_has_at($hay, $needle, $i) 8 9 17
1482 }
1483 2 return -1;
1484 }
1485  
1486 15 ▶sub index_of ($self, $recv, $elem) {
Subroutine index_of: called CC=3 SCAR=11.1
Pod undocumented
1487 15 ▶ return $self->_utf16_index_of($recv, $elem, 0) if defined $recv && !ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if defined $recv and not ref $recv 6 9 15
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
096
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1488 9 return _array_index_of($recv, $elem, 0);
1489 }
1490  
1491 9 ▶sub last_index_of ($self, $recv, $elem) {
Subroutine last_index_of: called CC=3 SCAR=11.1
Pod undocumented
1492 9 ▶ return $self->_utf16_index_of($recv, $elem, 1) if defined $recv && !ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if defined $recv and not ref $recv 4 5 9
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
054
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1493 5 return _array_index_of($recv, $elem, 1);
1494 }
1495  
1496 # `Array.prototype.at(i)` — supports negative indices (`.at(-1)` is
1497 # the last element); out-of-bounds returns JS `undefined` (`UNDEF`, which
1498 # renders as the empty string).
1499 # Matches the Go `bf_at` arithmetic (`length + i` for i < 0) so adapter
1500 # output stays symmetric. A plain-scalar (string) receiver is
1501 # `String.prototype.at`, indexed in UTF-16 code units (#3613). Half of a
1502 # surrogate pair comes back as U+FFFD, not the lone surrogate JS returns:
1503 # a Perl string could hold the code point, but two halves concatenated
1504 # stay two characters (they never rejoin into the astral one) and encode
1505 # to invalid UTF-8 on output, so the helper keeps its result valid text
1506 # instead (limitation `string-at-lone-surrogate`). Other references
1507 # return `undefined`.
1508  
1509 25 ▶sub at ($self, $recv, $i = $OMITTED) {
Subroutine at: called CC=10 SCAR=23.0
Pod undocumented
1510 # The index is ToIntegerOrInfinity'd, so an omitted, `undefined` or
1511 # `null` one reads element 0.
1512 25 ▶ $i = $UNDEF if _omitted($i);
Branch: 1 branch
BranchTrueFalseTotal
if _omitted($i) 2 23 25
1513 25 ▶ if (defined $recv && !ref($recv)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $recv and not ref $recv) 12 13 25
Condition100%3/3
defined $recv and not ref $recv
!ll&&!rl&&r
11212
MC/DC100%2/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table100%3/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1514 12 my $units = _utf16_units("$recv");
1515 12 my $idx = $self->_relative_index($i, scalar @$units);
1516 12 ▶ return $UNDEF unless defined $idx;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $idx 5 7 12
1517 7 my $u = $units->[$idx];
1518 7 ▶ return $u >= 0xD800 && $u <= 0xDFFF ? "\x{FFFD}" : chr($u);
Branch: 1 branch
BranchTrueFalseTotal
$u >= 55296 && $u <= 57343 ? : 1 6 7
Condition66%2/3
$u >= 55296 and $u <= 57343
!ll&&!rl&&r
601
MC/DC50%1/2
$u >= 55296 and $u <= 57343
$u >= 55296 $u <= 57343
Truth table66%2/3
A and B
A= $u >= 55296B= $u <= 57343
ABresult
0X0
100
111
1519 }
1520 13 ▶ return $UNDEF unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 2 11 13
1521 11 my $idx = $self->_relative_index($i, scalar @$recv);
1522 11 ▶ return defined $idx ? $recv->[$idx] : $UNDEF;
Branch: 1 branch
BranchTrueFalseTotal
defined $idx ? : 7 4 11
1523 }
1524  
1525 # `Array.prototype.at`'s index: ToIntegerOrInfinity, counted from the end
1526 # when negative; undef when it falls outside `[0, length)`.
1527 23 ▶sub _relative_index ($self, $value, $len) {
Subroutine _relative_index: called CC=4 SCAR=13.9
1528 23 my $idx = $self->_to_integer_or_infinity($value);
1529 23 ▶ $idx += $len if $idx < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx < 0 7 16 23
1530 23 ▶ return ($idx >= 0 && $idx < $len) ? $idx : undef;
Branch: 1 branch
BranchTrueFalseTotal
$idx >= 0 && $idx < $len ? : 14 9 23
Condition100%3/3
$idx >= 0 and $idx < $len
!ll&&!rl&&r
2714
MC/DC100%2/2
$idx >= 0 and $idx < $len
$idx >= 0 $idx < $len
Truth table100%3/3
A and B
A= $idx >= 0B= $idx < $len
ABresult
0X0
100
111
1531 }
1532  
1533 # `Array.prototype.concat(other)` — merges two arrays in order
1534 # into a new ARRAY ref. Non-array operands collapse to empty
1535 # (matches the Go `bf_concat` semantic so cross-adapter output
1536 # stays symmetric; differs from JS where a non-Array argument
1537 # with `Symbol.isConcatSpreadable` would be spread, a behaviour
1538 # the template-language path never observes).
1539  
1540 9 ▶sub concat ($self, $a, $b) {
Subroutine concat: called CC=3 SCAR=11.0
Pod undocumented
1541 9 my @out;
1542 9 ▶ push @out, @$a if ref($a) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $a eq "ARRAY" 6 3 9
1543 9 ▶ push @out, @$b if ref($b) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $b eq "ARRAY" 8 1 9
1544 9 return \@out;
1545 }
1546  
1547 # `Array.prototype.slice(start, end?)` AND `String.prototype.slice`
1548 # (the `string-slice` divergence) — carves out a sub-range. The
1549 # adapter emits the same call for both receiver shapes (it can't
1550 # disambiguate string vs. array at compile time), so this dispatches
1551 # at runtime on `ref($recv)`, mirroring `includes` above. Mirrors the
1552 # Go `bf_slice` arithmetic so adapter output stays symmetric:
1553 # - start < 0 → length + start (e.g. -1 = last index)
1554 # - end < 0 → length + end
1555 # - start < 0 after clamp → 0
1556 # - end > length → length
1557 # - start >= end → empty
1558 # - end omitted / `undefined` → "to length"; `null` is 0
1559 # Both bounds are ToIntegerOrInfinity'd (`null` and `undefined` are 0 as a
1560 # start). String length/positions are characters (`use utf8` is active), not
1561 # bytes. Any other receiver returns an empty ARRAY ref.
1562  
1563 23 ▶sub slice ($self, $recv, $start = $OMITTED, $end = $OMITTED) {
Subroutine slice: called CC=9 SCAR=22.0
Pod undocumented
1564 23 ▶ if (!ref($recv) && defined $recv) {
Branch: 1 branch
BranchTrueFalseTotal
if (not ref $recv and defined $recv) 5 18 23
Condition100%3/3
not ref $recv and defined $recv
!ll&&!rl&&r
1715
MC/DC100%2/2
not ref $recv and defined $recv
not ref $recv defined $recv
Truth table100%3/3
not(A) and B
A= not ref $recvB= defined $recv
ABresult
0X0
100
111
1565 5 my $len = CORE::length($recv);
1566 5 my ($s, $e) = $self->_clamp_slice_range($len, $start, $end);
1567 5 ▶ return '' if $s >= $e;
Branch: 1 branch
BranchTrueFalseTotal
if $s >= $e 1 4 5
1568 4 return substr($recv, $s, $e - $s);
1569 }
1570 18 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 2 16 18
1571 16 my $len = scalar @$recv;
1572 16 ▶ return [] if $len == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $len == 0 1 15 16
1573  
1574 15 my ($s, $e) = $self->_clamp_slice_range($len, $start, $end);
1575 15 ▶ return [] if $s >= $e;
Branch: 1 branch
BranchTrueFalseTotal
if $s >= $e 5 10 15
1576 10 return [ @{$recv}[$s .. $e - 1] ];
1577 }
1578  
1579 # Shared bounds arithmetic for both `slice` branches above.
1580 20 ▶sub _clamp_slice_range ($self, $len, $start, $end) {
Subroutine _clamp_slice_range: called CC=9 SCAR=22.3
1581 20 ▶ my $s = _omitted($start) ? 0 : $self->_to_integer_or_infinity($start);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($start) ? : 0 20 20
1582 20 ▶ $s = $len + $s if $s < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $s < 0 3 17 20
1583 20 ▶ $s = 0 if $s < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $s < 0 0 20 20
1584 20 ▶ $s = $len if $s > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $s > $len 1 19 20
1585  
1586 20 ▶ my $e = _omitted($end) ? $len : $self->_to_integer_or_infinity($end);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($end) ? : 9 11 20
1587 20 ▶ $e = $len + $e if $e < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $e < 0 2 18 20
1588 20 ▶ $e = 0 if $e < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $e < 0 0 20 20
1589 20 ▶ $e = $len if $e > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $e > $len 0 20 20
1590  
1591 20 return ($s, $e);
1592 }
1593  
1594 # `Array.prototype.reverse()` / `Array.prototype.toReversed()` —
1595 # both shapes share this lowering. SSR templates render a snapshot
1596 # of state, so JS's mutate-receiver (`reverse`) vs
1597 # return-new-array (`toReversed`) distinction has no template-
1598 # level meaning. Always returns a new ARRAY ref to keep callers
1599 # safe from accidental aliasing. Non-array receivers return an
1600 # empty ARRAY ref.
1601  
1602 8 ▶sub reverse ($self, $recv) {
Subroutine reverse: called CC=2 SCAR=6.9
Pod undocumented
1603 8 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 3 5 8
1604 5 return [ reverse @$recv ];
1605 }
1606  
1607 # `Array.prototype.flat(depth?)` (#1448 Tier C) — flatten nested ARRAY
1608 # refs `$depth` levels deep. A `$depth` of -1 is the `Infinity` sentinel
1609 # (flatten fully); 0 returns a shallow copy. Non-ARRAY elements are kept
1610 # as-is (JS only flattens nested arrays). Non-ARRAY receiver → [].
1611 4 ▶sub flat ($self, $recv, $depth = 1) {
Subroutine flat: called CC=7 SCAR=19.5
Pod undocumented
1612 4 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 4 4
1613 4 my @out;
1614 4 for my $el (@$recv) {
1615 5 ▶ if ($depth != 0 && ref($el) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($depth != 0 and ref $el eq 'ARRAY') { } 1 4 5
Condition100%3/3
$depth != 0 and ref $el eq "ARRAY"
!ll&&!rl&&r
311
MC/DC100%2/2
$depth != 0 and ref $el eq "ARRAY"
$depth != 0 ref $el eq "ARRAY"
Truth table100%3/3
A and B
A= $depth != 0B= ref $el eq "ARRAY"
ABresult
0X0
100
111
1616 1 ▶ my $next = $depth > 0 ? $depth - 1 : $depth;
Branch: 1 branch
BranchTrueFalseTotal
$depth > 0 ? : 1 0 1
1617 1 push @out, @{ $self->flat($el, $next) };
1618 }
1619 else {
1620 4 push @out, $el;
1621 }
1622 }
1623 4 return \@out;
1624 }
1625  
1626 # `Array.prototype.flat(depth)` with a DYNAMIC depth (#2094) — the depth is
1627 # itself an arbitrary runtime value (e.g. a prop), not a compile-time literal,
1628 # so it must be coerced with JS's `ToIntegerOrInfinity` before delegating to
1629 # `flat` above: truncate toward zero; negative -> 0; NaN / non-numeric -> 0;
1630 # +Infinity or a huge finite value -> flatten fully.
1631 #
1632 # Deliberately a SEPARATE entry point from `flat`, not a smarter version of
1633 # it: the literal-depth path's `-1` argument is a compile-time SENTINEL baked
1634 # into the template source, meaning "the source literally said `Infinity`". A
1635 # genuinely dynamic depth that happens to evaluate to `-1` at render time
1636 # means the OPPOSITE in real JS (`[1,[2]].flat(-1)` never recurses — same as
1637 # `.flat(0)`). Since both paths would otherwise hand the same literal-looking
1638 # argument to one shared function, that function couldn't tell which case
1639 # it's in — so the two stay separate. Mirrors Go's `FlatDynamicDepth` /
1640 # `coerceFlatDepth` in bf.go.
1641 2 ▶sub flat_dynamic ($self, $recv, $depth) {
Subroutine flat_dynamic: called CC=2 SCAR=6.9
Pod undocumented
1642 # An `undefined` depth is the default, 1; `null` coerces to 0.
1643 2 ▶ return $self->flat($recv, 1) if _omitted($depth);
Branch: 1 branch
BranchTrueFalseTotal
if _omitted($depth) 1 1 2
1644 1 return $self->flat($recv, _coerce_flat_depth($depth));
1645 }
1646  
1647 # _coerce_flat_depth: JS `ToIntegerOrInfinity` for a dynamic `.flat(depth)`
1648 # argument, collapsed to `flat`'s int contract (`-1` == flatten fully).
1649 #
1650 # Perl's scalar type system blurs string/number duality, so `looks_like_number`
1651 # (already the codebase's ToNumber-style coercion check, see BarefootJS::
1652 # Evaluator's `_to_number`) is reused here rather than inventing a new
1653 # convention. `looks_like_number` on this Perl (5.38) already recognises the
1654 # strings "Infinity" / "-Infinity" / "NaN" as numeric (verified empirically:
1655 # `perl -MScalar::Util=looks_like_number -e 'print looks_like_number("Infinity")'`
1656 # prints 1), and `$str + 0` on those strings yields the corresponding Perl
1657 # non-finite double, so no extra string special-casing is needed here.
1658 1 ▶sub _coerce_flat_depth ($depth) {
Subroutine _coerce_flat_depth: called CC=11 SCAR=47.2
1659 1 ▶ return 0 unless defined $depth;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $depth 1 0 1
1660 0 my $f;
1661 0 ▶ if (ref($depth) eq 'JSON::PP::Boolean') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $depth eq 'JSON::PP::Boolean') { } 0 0 0
elsif (not ref $depth and &looks_like_number($depth)) { } 0 0 0
1662 0 ▶ $f = $depth ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$depth ? : 0 0 0
1663 }
1664 ▶ elsif (!ref($depth) && looks_like_number($depth)) {
Condition0%0/3
not ref $depth and &looks_like_number($depth)
!ll&&!rl&&r
000
MC/DC0%0/2
not ref $depth and &looks_like_number($depth)
not ref $depth &looks_like_number($depth)
Truth table0%0/3
not(A) and B
A= not ref $depthB= &looks_like_number($depth)
ABresult
0X0
100
111
1665 0 $f = $depth + 0;
1666 }
1667 else {
1668 # undef handled above; anything else non-numeric (a plain string
1669 # that isn't a number, a HASH/ARRAY ref, ...) coerces via NaN.
1670 0 return 0;
1671 }
1672 0 ▶ return 0 if $f != $f; # NaN
Branch: 1 branch
BranchTrueFalseTotal
if $f != $f 0 0 0
1673 0 ▶ return -1 if $f == 9**9**9; # +Infinity -> flatten fully sentinel
Branch: 1 branch
BranchTrueFalseTotal
if $f == "Inf" 0 0 0
1674 0 ▶ return 0 if $f == -(9**9**9); # -Infinity -> 0
Branch: 1 branch
BranchTrueFalseTotal
if $f == "-Inf" 0 0 0
1675 0 my $trunc = int($f); # Perl's int() truncates toward zero
1676 0 ▶ return 0 if $trunc < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $trunc < 0 0 0 0
1677 0 ▶ return -1 if $trunc > 1_000_000; # huge finite ~= flatten fully
Branch: 1 branch
BranchTrueFalseTotal
if $trunc > 1000000 0 0 0
1678 0 return $trunc;
1679 }
1680  
1681 # `Array.prototype.flatMap(fn)` value-returning field projection
1682 # (#1448 Tier C) — map each element through a self / field projection,
1683 # then flatten one level. `field` reads a HASH-ref key (the raw JS prop
1684 # name, as `bf->reduce` does); a projected non-ARRAY value is kept as-is
1685 # (flatMap = map + flat(1)). Non-ARRAY receiver → [].
1686 1 ▶sub flat_map ($self, $recv, $key_kind, $key) {
Subroutine flat_map: called CC=4 SCAR=14.6
Pod undocumented
1687 1 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 1 1
1688 1 my @projected;
1689 1 for my $el (@$recv) {
1690 1 ▶ if ($key_kind eq 'field') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key_kind eq 'field') { } 1 0 1
1691 # JS `i => i.field` on a non-object, or a missing field, yields
1692 # `undefined`, not the element itself — so a scalar element
1693 # doesn't leak into the output.
1694 1 push @projected, _field_value($el, $key);
1695 }
1696 else {
1697 0 push @projected, $el;
1698 }
1699 }
1700 1 return $self->flat(\@projected, 1);
1701 }
1702  
1703 # `Array.prototype.flatMap(i => [i.a, i.b])` — array-literal tuple
1704 # projection (#1448 Tier C). Each `@specs` entry is a [kind, key] arrayref
1705 # (['self', ''] or ['field', 'a']). For each element, every leaf's value
1706 # is appended in order. flat(1) removes only the literal wrapper, so an
1707 # array-valued leaf is appended verbatim (no spread) — i.e. just append
1708 # each leaf. A non-HASH element under a `field` leaf, or a missing field,
1709 # yields `undefined` (JS `i.field`). Non-ARRAY receiver → [].
1710 0 ▶sub flat_map_tuple ($self, $recv, @specs) {
Subroutine flat_map_tuple: not called CC=5 SCAR=34.0
Pod undocumented
1711 0 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 0 0 0
1712 0 my @out;
1713 0 for my $el (@$recv) {
1714 0 for my $spec (@specs) {
1715 0 my ($kind, $key) = @$spec;
1716 0 ▶ if ($kind eq 'field') {
Branch: 1 branch
BranchTrueFalseTotal
if ($kind eq 'field') { } 0 0 0
1717 0 push @out, _field_value($el, $key);
1718 }
1719 else {
1720 0 push @out, $el;
1721 }
1722 }
1723 }
1724 0 return \@out;
1725 }
1726  
1727 # `String.prototype.trim()` — strip leading + trailing whitespace.
1728 # JS's `String.prototype.trim` matches `\s` in the Unicode sense
1729 # (any whitespace including non-breaking space U+00A0); Perl's `\s`
1730 # inside a regex with `/u` flag is the same. Undef receivers return
1731 # the empty string (matches JS's `String(undefined).trim()` which
1732 # would be "undefined" → "undefined", but in our template context
1733 # undef commonly means "missing prop"; rendering the empty string
1734 # is the safer choice and mirrors the JS-compat divergence we
1735 # already document for `bf->string(undef) === ""`).
1736  
1737 11 ▶sub trim ($self, $recv) {
Subroutine trim: called CC=3 SCAR=11.0
Pod undocumented
1738 11 ▶ return '' if _nullish($recv);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($recv) 1 10 11
1739 10 ▶ return '' if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 2 8 10
1740 8 my $s = "$recv";
1741 8 $s =~ s/^\s+|\s+$//gu;
1742 8 return $s;
1743 }
1744  
1745 # `String.prototype.trimStart()` / `.trimEnd()` — the one-sided
1746 # siblings of `trim` above (#2183 follow-up), same `\s` /u regex
1747 # semantics restricted to one side.
1748  
1749 7 ▶sub trim_start ($self, $recv) {
Subroutine trim_start: called CC=3 SCAR=11.0
Pod undocumented
1750 7 ▶ return '' if _nullish($recv);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($recv) 1 6 7
1751 6 ▶ return '' if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 1 5 6
1752 5 my $s = "$recv";
1753 5 $s =~ s/^\s+//u;
1754 5 return $s;
1755 }
1756  
1757 7 ▶sub trim_end ($self, $recv) {
Subroutine trim_end: called CC=3 SCAR=11.0
Pod undocumented
1758 7 ▶ return '' if _nullish($recv);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($recv) 1 6 7
1759 6 ▶ return '' if ref($recv);
Branch: 1 branch
BranchTrueFalseTotal
if ref $recv 1 5 6
1760 5 my $s = "$recv";
1761 5 $s =~ s/\s+$//u;
1762 5 return $s;
1763 }
1764  
1765 # `Number.prototype.toFixed(digits)` (#1897) — fixed-decimal string with
1766 # zero-padding. JS rounds the scaled integer half toward +Infinity (the
1767 # spec's "pick the larger n" tie-break), so `(2.5).toFixed(0)` is "3";
1768 # bare `sprintf("%.*f")` would round half-to-even ("2"), diverging. Scale
1769 # by 10**digits, round with `floor(x + 0.5)` (the same tie-break the
1770 # `round` helper uses), then format the exact multiple. A negative
1771 # `digits` clamps to 0, mirroring how the adapters default an omitted
1772 # argument.
1773 1 ▶sub to_fixed ($self, $value, $digits = $OMITTED) {
Subroutine to_fixed: called CC=7 SCAR=21.5
Pod undocumented
1774 1 my $n = $self->number($value);
1775 # JS toFixed returns the STRINGS "NaN" / "Infinity" / "-Infinity" for
1776 # non-finite inputs; the numeric values would stringify per-platform
1777 # ("nan"/"inf"/...) and diverge.
1778 1 ▶ return 'NaN' if _is_nan($n);
Branch: 1 branch
BranchTrueFalseTotal
if _is_nan($n) 0 1 1
1779 1 ▶ return $n < 0 ? '-Infinity' : 'Infinity' if _is_inf($n);
Branch: 2 branches
BranchTrueFalseTotal
if _is_inf($n) 0 1 1
$n < 0 ? : 0 0 0
1780 # An omitted or `undefined` digit count is 0, as ToIntegerOrInfinity
1781 # makes `null` too.
1782 1 ▶ $digits = _omitted($digits) ? 0 : $self->_to_integer_or_infinity($digits);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($digits) ? : 1 0 1
1783 1 ▶ $digits = 0 if $digits < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $digits < 0 0 1 1
1784 1 my $factor = 10 ** $digits;
1785 # Scaled as doubles, so `(1.005).toFixed(2)` sees JS's 100.49999… on a
1786 # perl whose NV is wider than a double (#3454).
1787 1 my $rounded = POSIX::floor(_as_double(_as_double($n) * $factor) + 0.5);
1788 1 return sprintf('%.*f', $digits, $rounded / $factor);
1789 }
1790  
1791 # `String.prototype.split(sep)` (#1448 Tier B) — string → ARRAY ref.
1792 #
1793 # Two JS-parity wrinkles drive the helper (a bare `split` emit would
1794 # diverge from both JS and Go):
1795 #
1796 # * Perl's `split` treats its first argument as a *regex*, so a
1797 # separator like '.' or '|' would match far too much. We
1798 # `quotemeta` it to force literal-string matching, mirroring JS's
1799 # string-separator semantics (the regex-separator form stays
1800 # refused upstream — see the parser arm).
1801 # * Perl's `split` drops trailing empty fields by default; JS keeps
1802 # them (`"a,".split(",")` is `["a", ""]`). Passing the `-1` limit
1803 # preserves them, matching JS and Go's `strings.Split`.
1804 #
1805 # An empty separator splits into individual characters (JS + Go agree).
1806 # Undef receiver renders as the single-element `['']` — the same
1807 # "missing prop → empty string" convention `bf->trim` uses.
1808  
1809 21 ▶sub split ($self, $recv, $sep = $OMITTED, $limit = $OMITTED) {
Subroutine split: called CC=10 SCAR=23.0
Pod undocumented
1810 21 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 20 1 21
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
1020
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1811  
1812 21 my @parts;
1813 21 ▶ if (_omitted($sep)) {
Branch: 3 branches
BranchTrueFalseTotal
if (_omitted($sep)) { } 2 19 21
elsif (($sep = _js_string($sep)) eq '') { } 2 17 19
elsif ($s eq '') { } 1 16 17
1814 # No separator → the whole string in a single-element array
1815 # (matches JS `"x".split()` / `.split(undefined)`). Any other one is
1816 # ToString'd (`null` splits on "null").
1817 2 @parts = ($s);
1818 }
1819 elsif (($sep = _js_string($sep)) eq '') {
1820 # Empty separator → individual characters. No `-1` limit here:
1821 # on an empty pattern Perl's `split` with `-1` appends a spurious
1822 # trailing empty field ("abc" → 'a','b','c',''), which JS/Go don't.
1823 2 @parts = split //, $s;
1824 }
1825 elsif ($s eq '') {
1826 # Empty input with a non-empty separator: JS `"".split(",")` is
1827 # `[""]` and Go's `strings.Split("", ",")` is `[""]`, but Perl's
1828 # `split /,/, ''` returns the empty list — special-case for parity.
1829 1 @parts = ('');
1830 }
1831 else {
1832 # `quotemeta` forces literal-string matching (JS string-separator
1833 # semantics); the `-1` keeps trailing empty fields (JS keeps them,
1834 # Perl's bare `split` drops them).
1835 16 my $q = quotemeta("$sep");
1836 16 @parts = split /$q/, $s, -1;
1837 }
1838  
1839 # Optional `limit` caps the number of pieces (JS `split(sep, limit)`):
1840 # an omitted or `undefined` one is unbounded, any other one ToUint32'd
1841 # (`null` and NaN are 0 → empty; a negative limit wraps to a large one,
1842 # effectively unbounded).
1843 21 ▶ unless (_omitted($limit)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_omitted($limit)) 5 16 21
1844 5 my $n = _to_uint32($limit);
1845 5 ▶ @parts = @parts[0 .. $n - 1] if $n < scalar @parts;
Branch: 1 branch
BranchTrueFalseTotal
if $n < scalar @parts 3 2 5
1846 }
1847  
1848 21 return [@parts];
1849 }
1850  
1851 # `String.prototype.startsWith(prefix, position?)` (#1448 Tier B) —
1852 # string → boolean (1 / 0). `substr`-anchored literal comparison mirrors
1853 # Go's `strings.HasPrefix`. An empty prefix is always true (JS parity);
1854 # undef / non-string receivers coerce to the empty string first. The
1855 # optional `position` re-anchors the test (UTF-16 code units, clamped to
1856 # `[0, length]`), matching JS `"abc".startsWith("b", 1)`.
1857  
1858 17 ▶sub starts_with ($self, $recv, $prefix, $position = $OMITTED) {
Subroutine starts_with: called CC=8 SCAR=20.8
Pod undocumented
1859 17 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 15 2 17
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
2015
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1860 17 my $p = _js_string($prefix);
1861 # An omitted or `undefined` position is 0; `null` is 0 too.
1862 17 ▶ unless (_omitted($position)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_omitted($position)) 9 8 17
1863 # `position` counts UTF-16 code units, like JS (#3613).
1864 9 my $units = _utf16_units($s);
1865 9 my $n = $self->_to_integer_or_infinity($position);
1866 9 ▶ $n = 0 if $n < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 0 1 8 9
1867 9 ▶ $n = @$units if $n > @$units;
Branch: 1 branch
BranchTrueFalseTotal
if $n > @$units 2 7 9
1868 9 return _utf16_has_at($units, _utf16_units($p), $n);
1869 }
1870 8 ▶ return substr($s, 0, CORE::length $p) eq $p ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
substr($s, 0, CORE::length $p) eq $p ? : 5 3 8
1871 }
1872  
1873 # `String.prototype.endsWith(suffix, endPosition?)` (#1448 Tier B) —
1874 # string → boolean (1 / 0). Mirrors Go's `strings.HasSuffix`. An empty
1875 # suffix is always true (JS parity); a suffix longer than the string is
1876 # false. `substr($s, -length $x)` would mis-read the whole string when
1877 # `length $x == 0`, so that case short-circuits. The optional
1878 # `endPosition` treats the string as if it were only that many UTF-16
1879 # code units long (clamped to `[0, length]`), matching JS
1880 # `"abc".endsWith("b", 2)`.
1881  
1882 17 ▶sub ends_with ($self, $recv, $suffix, $end_position = $OMITTED) {
Subroutine ends_with: called CC=10 SCAR=23.1
Pod undocumented
1883 17 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 17 0 17
Condition33%1/3
defined $recv and not ref $recv
!ll&&!rl&&r
0017
MC/DC0%0/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table33%1/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1884 17 my $x = _js_string($suffix);
1885 # An omitted or `undefined` endPosition is the length; `null` is 0.
1886 17 ▶ unless (_omitted($end_position)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_omitted($end_position)) 10 7 17
1887 # `endPosition` counts UTF-16 code units, like JS (#3613).
1888 10 my $units = _utf16_units($s);
1889 10 my $needle = _utf16_units($x);
1890 10 my $e = $self->_to_integer_or_infinity($end_position);
1891 10 ▶ $e = 0 if $e < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $e < 0 1 9 10
1892 10 ▶ $e = @$units if $e > @$units;
Branch: 1 branch
BranchTrueFalseTotal
if $e > @$units 2 8 10
1893 10 return _utf16_has_at($units, $needle, $e - @$needle);
1894 }
1895 7 ▶ return 1 if $x eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $x eq "" 1 6 7
1896 6 ▶ return 0 if CORE::length($s) < CORE::length($x);
Branch: 1 branch
BranchTrueFalseTotal
if CORE::length $s < CORE::length $x 1 5 6
1897 5 ▶ return substr($s, -CORE::length $x) eq $x ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
substr($s, -CORE::length($x)) eq $x ? : 3 2 5
1898 }
1899  
1900 # `String.prototype.replace(pattern, replacement)` — string-pattern
1901 # form only (#1448 Tier B), replacing the FIRST occurrence (JS string-
1902 # pattern semantics). Spliced via index/substr rather than `s///` so
1903 # BOTH the pattern and the replacement are literal: no Perl regex
1904 # metacharacters in the pattern and no `$1` / `$&` interpolation in the
1905 # replacement. Go's `bf_replace` (strings.Replace, n=1) treats the
1906 # replacement literally too, so the two adapters stay byte-equal — this
1907 # diverges from JS only for replacement strings containing `$`-patterns
1908 # (rare in template position). An empty pattern inserts the replacement
1909 # at the front (`"abc".replace("", "X")` → "Xabc"), matching JS + Go.
1910  
1911 9 ▶sub replace ($self, $recv, $pattern, $replacement) {
Subroutine replace: called CC=5 SCAR=16.1
Pod undocumented
1912 9 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 8 1 9
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
108
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1913 # The pattern and the replacement are JS ToString'd.
1914 9 my $o = _js_string($pattern);
1915 9 my $n = _js_string($replacement);
1916 9 ▶ return $n . $s if $o eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $o eq "" 1 8 9
1917 8 my $i = index($s, $o);
1918 8 ▶ return $s if $i < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $i < 0 2 6 8
1919 6 return substr($s, 0, $i) . $n . substr($s, $i + CORE::length($o));
1920 }
1921  
1922 # `String.prototype.replaceAll(pattern, replacement)` — string-pattern
1923 # form only (#2182), replacing EVERY occurrence (the all-occurrences
1924 # sibling of `replace` above). Same literal-splice approach (no regex
1925 # metacharacters, no `$1`/`$&` interpolation) as `replace`, looped
1926 # forward from each match's end. An empty pattern inserts the
1927 # replacement at every boundary, including before the first and after
1928 # the last character (`"abc".replaceAll("", "X")` -> "XaXbXcX"),
1929 # matching JS.
1930  
1931 0 ▶sub replace_all ($self, $recv, $pattern, $replacement) {
Subroutine replace_all: not called CC=5 SCAR=34.0
Pod undocumented
1932 0 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 0 0 0
Condition0%0/3
defined $recv and not ref $recv
!ll&&!rl&&r
000
MC/DC0%0/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table0%0/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
1933 # The pattern and the replacement are JS ToString'd.
1934 0 my $o = _js_string($pattern);
1935 0 my $n = _js_string($replacement);
1936 0 ▶ return CORE::join($n, '', split(//, $s), '') if $o eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $o eq "" 0 0 0
1937 0 my $out = '';
1938 0 my $pos = 0;
1939 0 my $olen = CORE::length($o);
1940 0 while (1) {
1941 0 my $i = index($s, $o, $pos);
1942 0 ▶ last if $i < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $i < 0 0 0 0
1943 0 $out .= substr($s, $pos, $i - $pos) . $n;
1944 0 $pos = $i + $olen;
1945 }
1946 0 $out .= substr($s, $pos);
1947 0 return $out;
1948 }
1949  
1950 # `queryHref(base, { … })` (#2042) — build `"$base?k=v&…"` from a flat list of
1951 # (guard, key, value) triples. A pair is included iff its guard is truthy AND
1952 # its value is a non-empty string, mirroring the client `queryHref`'s `if
1953 # (value)` over string values: the adapter passes the guard `1` for a plain
1954 # `key: v`, or the lowered condition for `key: cond ? v : undefined`. Repeating a
1955 # key overwrites the value at its first position (`URLSearchParams.set`
1956 # semantics).
1957 #
1958 # A value may instead be an array ref, which APPENDS one pair per non-empty
1959 # member (`{ tag => ['a','b'] }` → `tag=a&tag=b`, i.e. `URLSearchParams.append`);
1960 # empty members are skipped, so an empty/all-empty array contributes nothing.
1961 #
1962 # Keys/values are form-encoded to equal the browser render byte-for-byte; no
1963 # surviving pair yields the bare base.
1964 5 ▶sub query ($self, $base, @triples) {
Subroutine query: called CC=17 SCAR=29.5
Pod undocumented
1965 5 ▶ my $b = defined $base && !ref($base) ? "$base" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $base && !ref($base) ? : 5 0 5
Condition33%1/3
defined $base and not ref $base
!ll&&!rl&&r
005
MC/DC0%0/2
defined $base and not ref $base
defined $base not ref $base
Truth table33%1/3
A and not(B)
A= defined $baseB= not ref $base
ABresult
0X0
100
111
1966 5 my (@pairs, %pos);
1967 5 my $i = 0;
1968 5 ▶ while ($i + 2 < @triples) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i + 2 < @triples) 8 5 13
1969 8 my ($guard, $key, $val) = @triples[$i, $i + 1, $i + 2];
1970 8 $i += 3;
1971 8 ▶ next unless $guard;
Branch: 1 branch
BranchTrueFalseTotal
unless $guard 0 8 8
1972 8 ▶ $key = defined $key && !ref($key) ? "$key" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $key && !ref($key) ? : 8 0 8
Condition33%1/3
defined $key and not ref $key
!ll&&!rl&&r
008
MC/DC0%0/2
defined $key and not ref $key
defined $key not ref $key
Truth table33%1/3
A and not(B)
A= defined $keyB= not ref $key
ABresult
0X0
100
111
1973 8 ▶ if (ref($val) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "ARRAY") 1 7 8
1974 # Append each non-empty member; appended pairs never overwrite, so
1975 # they don't participate in the set()-position map.
1976 1 for my $m (@$val) {
1977 3 ▶ my $s = defined $m && !ref($m) ? "$m" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $m && !ref($m) ? : 3 0 3
Condition33%1/3
defined $m and not ref $m
!ll&&!rl&&r
003
MC/DC0%0/2
defined $m and not ref $m
defined $m not ref $m
Truth table33%1/3
A and not(B)
A= defined $mB= not ref $m
ABresult
0X0
100
111
1978 3 ▶ next if $s eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $s eq "" 1 2 3
1979 2 push @pairs, [$key, $s];
1980 }
1981 1 next;
1982 }
1983 7 ▶ $val = defined $val && !ref($val) ? "$val" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val && !ref($val) ? : 5 2 7
Condition66%2/3
defined $val and not ref $val
!ll&&!rl&&r
205
MC/DC50%1/2
defined $val and not ref $val
defined $val not ref $val
Truth table66%2/3
A and not(B)
A= defined $valB= not ref $val
ABresult
0X0
100
111
1984 7 ▶ next if $val eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $val eq "" 2 5 7
1985 5 ▶ if (exists $pos{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $pos{$key}) { } 1 4 5
1986 1 $pairs[$pos{$key}][1] = $val;
1987 }
1988 else {
1989 4 $pos{$key} = scalar @pairs;
1990 4 push @pairs, [$key, $val];
1991 }
1992 }
1993 5 ▶ return $b unless @pairs;
Branch: 1 branch
BranchTrueFalseTotal
unless @pairs 1 4 5
1994 4 return "$b?" . CORE::join('&', map { _form_escape($_->[0]) . '=' . _form_escape($_->[1]) } @pairs);
1995 }
1996  
1997 # `String.prototype.repeat(n)` — the receiver concatenated n times
1998 # (#1448 Tier B), via Perl's `x` operator. JS throws RangeError for a
1999 # negative count, but SSR templates degrade to the empty string rather
2000 # than dying mid-render, so a count <= 0 returns "" (Go's `bf_repeat`
2001 # applies the same clamp). The count is truncated toward zero
2002 # (`int`), matching JS's ToIntegerOrInfinity on `"a".repeat(3.7)`.
2003  
2004 8 ▶sub repeat ($self, $recv, $count = $OMITTED) {
Subroutine repeat: called CC=6 SCAR=17.9
Pod undocumented
2005 8 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 7 1 8
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
107
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
2006 # ToIntegerOrInfinity: an omitted, `undefined` or `null` count is 0.
2007 8 ▶ my $n = $self->_to_integer_or_infinity(_omitted($count) ? $UNDEF : $count);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($count) ? : 1 7 8
2008 8 ▶ return $n <= 0 ? '' : $s x $n;
Branch: 1 branch
BranchTrueFalseTotal
$n <= 0 ? : 3 5 8
2009 }
2010  
2011 # `String.prototype.padStart` / `padEnd` (#1448 Tier B) — pad the
2012 # receiver to `$target` characters with `$pad` (default a single space)
2013 # repeated and truncated to fill, prepended or appended. Length is
2014 # measured in characters (Perl `length`), matching Go's rune-based
2015 # `bf_pad_*` — diverges from JS's UTF-16-unit length only for
2016 # astral-plane input. An empty pad, or a receiver already >= `$target`,
2017 # returns the receiver unchanged (JS parity). The `$target` is
2018 # truncated toward zero (JS ToLength on the first arg).
2019  
2020 12 ▶sub _pad ($self, $s, $target, $pad, $at_start) {
Subroutine _pad: called CC=6 SCAR=17.9
2021 # An omitted or `undefined` pad string is a space; any other one is
2022 # ToString'd (`null` pads with "null"). The target is ToIntegerOrInfinity'd.
2023 12 ▶ $pad = _omitted($pad) ? ' ' : _js_string($pad);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($pad) ? : 3 9 12
2024 12 ▶ return $s if $pad eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $pad eq "" 1 11 12
2025 11 my $len = CORE::length $s;
2026 11 ▶ my $t = $self->_to_integer_or_infinity(_omitted($target) ? $UNDEF : $target);
Branch: 1 branch
BranchTrueFalseTotal
_omitted($target) ? : 0 11 11
2027 11 ▶ return $s if $len >= $t;
Branch: 1 branch
BranchTrueFalseTotal
if $len >= $t 1 10 11
2028 10 my $need = $t - $len;
2029 # Repeat enough copies to cover $need, then trim to exactly $need.
2030 10 my $fill = substr($pad x (int($need / CORE::length($pad)) + 1), 0, $need);
2031 10 ▶ return $at_start ? $fill . $s : $s . $fill;
Branch: 1 branch
BranchTrueFalseTotal
$at_start ? : 7 3 10
2032 }
2033  
2034 9 ▶sub pad_start ($self, $recv, $target = $OMITTED, $pad = $OMITTED) {
Subroutine pad_start: called CC=5 SCAR=16.2
Pod undocumented
2035 9 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 8 1 9
Condition66%2/3
defined $recv and not ref $recv
!ll&&!rl&&r
108
MC/DC50%1/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table66%2/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
2036 9 return $self->_pad($s, $target, $pad, 1);
2037 }
2038  
2039 3 ▶sub pad_end ($self, $recv, $target = $OMITTED, $pad = $OMITTED) {
Subroutine pad_end: called CC=5 SCAR=17.8
Pod undocumented
2040 3 ▶ my $s = defined $recv && !ref($recv) ? "$recv" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $recv && !ref($recv) ? : 3 0 3
Condition33%1/3
defined $recv and not ref $recv
!ll&&!rl&&r
003
MC/DC0%0/2
defined $recv and not ref $recv
defined $recv not ref $recv
Truth table33%1/3
A and not(B)
A= defined $recvB= not ref $recv
ABresult
0X0
100
111
2041 3 return $self->_pad($s, $target, $pad, 0);
2042 }
2043  
2044 # JS `ToUint32` (`split`'s limit): NaN and the infinities are 0.
2045 5 ▶sub _to_uint32 ($value) {
Subroutine _to_uint32: called CC=6 SCAR=19.1
2046 5 my $n = _js_number($value);
2047 5 ▶ return 0 if $n != $n || $n == 9**9**9 || $n == -(9**9**9);
Branch: 1 branch
BranchTrueFalseTotal
if $n != $n or $n == "Inf" or $n == "-Inf" 0 5 5
Condition33%2/6
$n != $n or $n == "Inf" or $n == "-Inf"
l!l&&r!l&&!r
005
$n != $n or $n == "Inf"
l!l&&r!l&&!r
005
MC/DC0%0/3
$n != $n or $n == "Inf" or $n == "-Inf"
$n != $n $n == "Inf" $n == "-Inf"
Truth table25%1/4
A or B or C
A= $n != $nB= $n == "Inf"C= $n == "-Inf"
ABCresult
1XX1
01X1
0011
0000
2048 5 ▶ my $t = $n < 0 ? POSIX::ceil($n) : POSIX::floor($n);
Branch: 1 branch
BranchTrueFalseTotal
$n < 0 ? : 1 4 5
2049 5 $t = POSIX::fmod($t, 4294967296);
2050 5 ▶ $t += 4294967296 if $t < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $t < 0 1 4 5
2051 5 return $t;
2052 }
2053  
2054 # A row field's value: JS `item.key`, `undefined` when the row has no such
2055 # field (or is no object).
2056 25 ▶sub _field_value ($item, $key) {
Subroutine _field_value: called CC=3 SCAR=11.1
2057 25 ▶ return $UNDEF unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 25 25
2058 25 ▶ return exists $item->{$key} ? $item->{$key} : $UNDEF;
Branch: 1 branch
BranchTrueFalseTotal
exists $item->{$key} ? : 24 1 25
2059 }
2060  
2061 # `Array.prototype.sort(cmp)` / `Array.prototype.toSorted(cmp)`
2062 # lowering (#1448 Tier B). Non-mutating — JS's mutate-vs-new
2063 # distinction is moot in SSR template context.
2064 #
2065 # Opts hash-ref. The compiler emits a `keys` list of per-key hashes
2066 # in priority order; each hash carries:
2067 #
2068 # key_kind => 'self' | 'field'
2069 # key => '' when key_kind eq 'self'; field name verbatim
2070 # from the comparator AST (e.g. 'price', 'createdAt')
2071 # when key_kind eq 'field' — no case normalisation
2072 # applied. Perl hash lookups are case-sensitive so
2073 # the key here must match the actual hash key the
2074 # user populated.
2075 # compare_type => 'numeric' | 'string' | 'auto'
2076 # direction => 'asc' | 'desc'
2077 #
2078 # Accepted comparator catalogue (gated upstream at parse time —
2079 # anything outside refuses with BF101 before reaching this helper):
2080 #
2081 # (a,b) => a.f - b.f → field, numeric
2082 # (a,b) => a - b → self, numeric
2083 # (a,b) => a[.f].localeCompare(b[.f]) → field|self, string
2084 # (a,b) => a.f > b.f ? 1 : -1 → field|self, auto
2085 # any of the above ||-chained → multi-key tie-breaks
2086 # (and reversed-operand variants for `desc`).
2087 #
2088 # `auto` (relational-ternary lowering) compares numerically when both
2089 # keys `looks_like_number`, else lexically — Go's `bf_sort` applies the
2090 # same rule so the two template adapters stay byte-equal.
2091 #
2092 # A future `nulls => 'first' | 'last'` knob can land per key without
2093 # churn — the opts hash is the right place to grow.
2094  
2095 # Evaluator-driven sort / reduce (#2018): the comparator / reducer body rides
2096 # as a serialized-ParsedExpr JSON string and is evaluated per element, delegating
2097 # to the shared BarefootJS::Evaluator. The adapter emits `bf->sort_eval(...)` /
2098 # `bf->reduce_eval(...)` for any pure comparator / reducer body; a body it can't
2099 # model (e.g. localeCompare) keeps the legacy `bf->sort` / `bf->reduce` path.
2100 1 ▶sub sort_eval ($self, $recv, $cmp_json, $param_a, $param_b, $base_env = {}) {
Subroutine sort_eval: called CC=2 SCAR=6.9
Pod undocumented
2101 1 return BarefootJS::Evaluator::sort_by_json($recv, $cmp_json, $param_a, $param_b, $base_env);
2102 }
2103  
2104 0 ▶sub reduce_eval ($self, $recv, $body_json, $acc_name, $item_name, $init, $direction = 'left', $base_env = {}) {
Subroutine reduce_eval: not called CC=3 SCAR=24.8
Pod undocumented
2105 0 return BarefootJS::Evaluator::fold_json($recv, $body_json, $acc_name, $item_name, $init, $direction, $base_env);
2106 }
2107  
2108 # Evaluator-driven higher-order predicates (#2018, P2): the predicate body
2109 # rides as a serialized-ParsedExpr JSON string evaluated per element, delegating
2110 # to the shared BarefootJS::Evaluator. The adapter emits `bf->filter_eval(...)`
2111 # etc. for any pure predicate; a body it can't model (e.g. a method-call
2112 # predicate) keeps the legacy `grep` / `bf->find` path. `find_eval` /
2113 # `find_index_eval` take a `$forward` flag (false → findLast / findLastIndex).
2114 0 ▶sub filter_eval ($self, $recv, $pred_json, $param, $base_env = {}) {
Subroutine filter_eval: not called CC=2 SCAR=17.9
Pod undocumented
2115 0 return BarefootJS::Evaluator::filter_json($recv, $pred_json, $param, $base_env);
2116 }
2117  
2118 0 ▶sub every_eval ($self, $recv, $pred_json, $param, $base_env = {}) {
Subroutine every_eval: not called CC=2 SCAR=17.9
Pod undocumented
2119 0 return BarefootJS::Evaluator::every_json($recv, $pred_json, $param, $base_env);
2120 }
2121  
2122 0 ▶sub some_eval ($self, $recv, $pred_json, $param, $base_env = {}) {
Subroutine some_eval: not called CC=2 SCAR=17.9
Pod undocumented
2123 0 return BarefootJS::Evaluator::some_json($recv, $pred_json, $param, $base_env);
2124 }
2125  
2126 0 ▶sub find_eval ($self, $recv, $pred_json, $param, $forward = 1, $base_env = {}) {
Subroutine find_eval: not called CC=3 SCAR=24.8
Pod undocumented
2127 0 return BarefootJS::Evaluator::find_json($recv, $pred_json, $param, $forward, $base_env);
2128 }
2129  
2130 0 ▶sub find_index_eval ($self, $recv, $pred_json, $param, $forward = 1, $base_env = {}) {
Subroutine find_index_eval: not called CC=3 SCAR=24.8
Pod undocumented
2131 0 return BarefootJS::Evaluator::find_index_json($recv, $pred_json, $param, $forward, $base_env);
2132 }
2133  
2134 0 ▶sub flat_map_eval ($self, $recv, $proj_json, $param, $base_env = {}) {
Subroutine flat_map_eval: not called CC=2 SCAR=17.9
Pod undocumented
2135 0 return BarefootJS::Evaluator::flat_map_json($recv, $proj_json, $param, $base_env);
2136 }
2137  
2138 # Value-producing `.map(cb)` (#2073): project each element through the
2139 # serialized projection body, one result per element (no flatten). Composes
2140 # through the array-method chain (`.map(cb).join(' ')`).
2141 0 ▶sub map_eval ($self, $recv, $proj_json, $param, $base_env = {}) {
Subroutine map_eval: not called CC=2 SCAR=17.9
Pod undocumented
2142 0 return BarefootJS::Evaluator::map_json($recv, $proj_json, $param, $base_env);
2143 }
2144  
2145 17 ▶sub sort ($self, $recv, $opts = {}) {
Subroutine sort: called CC=10 SCAR=23.2
Pod undocumented
2146 17 ▶ return [] unless ref($recv) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $recv eq "ARRAY" 3 14 17
2147  
2148 # Normalise the per-key specs (priority order, length >= 1).
2149 my @spec = map {
2150 {
2151 key_kind => $_->{key_kind} // 'self',
2152 key => $_->{key} // '',
2153 compare_type => $_->{compare_type} // 'numeric',
2154 16 ▶ direction => $_->{direction} // 'asc',
Condition62%5/8
$_->{"key_kind"} // "self"
l!l
160
$_->{"key"} // ""
l!l
97
$_->{"compare_type"} // "numeric"
l!l
160
$_->{"direction"} // "asc"
l!l
160
MC/DC0%0/1
$_->{"key_kind"} // "self"
$_->{"key_kind"}
MC/DC100%1/1
$_->{"key"} // ""
$_->{"key"}
MC/DC0%0/1
$_->{"compare_type"} // "numeric"
$_->{"compare_type"}
MC/DC0%0/1
$_->{"direction"} // "asc"
$_->{"direction"}
Truth table50%1/2
A
A= $_->{"key_kind"}
Aresult
11
00
Truth table100%2/2
A
A= $_->{"key"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"compare_type"}
Aresult
11
00
Truth table50%1/2
A
A= $_->{"direction"}
Aresult
11
00
2155 }
2156 14 ▶ } @{ $opts->{keys} // [] };
Condition50%1/2
$opts->{"keys"} // []
l!l
140
MC/DC0%0/1
$opts->{"keys"} // []
$opts->{"keys"}
Truth table50%1/2
A
A= $opts->{"keys"}
Aresult
11
00
2157 14 ▶ return [ @$recv ] unless @spec;
Branch: 1 branch
BranchTrueFalseTotal
unless @spec 0 14 14
2158  
2159 # JS moves every `undefined` element to the end without handing it to
2160 # the comparator.
2161 14 my @tail = grep { _undef_p($_) } @$recv;
2162  
2163 # Schwartzian transform: project each item to all its sort keys
2164 # once, then compare projected keys. Cheaper than re-resolving the
2165 # field accessors inside every comparison for non-trivial arrays.
2166 my @keyed = map {
2167 40 my $item = $_;
2168 my @ks = map {
2169 40 ▶ $_->{key_kind} eq 'field' ? _field_value($item, $_->{key}) : $item;
Branch: 1 branch
BranchTrueFalseTotal
$_->{'key_kind'} eq 'field' ? : 24 22 46
2170 } @spec;
2171 40 [ \@ks, $item ];
2172 14 } grep { !_undef_p($_) } @$recv;
2173  
2174 40 ▶ my $cmp = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2175 40 for my $i (0 .. $#spec) {
2176 44 my $sp = $spec[$i];
2177 44 my $c = _compare_sort_key($a->[0][$i], $b->[0][$i], $sp->{compare_type});
2178 44 ▶ next if $c == 0; # tie on this key — try the next
Branch: 1 branch
BranchTrueFalseTotal
if $c == 0 7 37 44
2179 37 ▶ return $sp->{direction} eq 'desc' ? -$c : $c;
Branch: 1 branch
BranchTrueFalseTotal
$sp->{'direction'} eq 'desc' ? : 9 28 37
2180 }
2181 3 return 0;
2182 14 };
2183  
2184 14 my @sorted = sort $cmp @keyed;
2185 14 return [ (map { $_->[1] } @sorted), @tail ];
2186 }
2187  
2188 # Compare two projected keys, ascending orientation (-1 / 0 / 1); the
2189 # caller negates for 'desc'. 'auto' compares numerically when both
2190 # keys look like numbers, else lexically (matches Go's `bf_sort`).
2191 # A nil key (`null` / `undefined`) reads as '' lexically and `null` as 0
2192 # numerically, so the order stays total without warnings; a numeric
2193 # `a.f - b.f` over an `undefined` key is NaN, which the sort reads as
2194 # "equal".
2195 44 ▶sub _compare_sort_key ($av, $bv, $compare_type) {
Subroutine _compare_sort_key: called CC=15 SCAR=29.7
2196 44 ▶ my $str = sub ($v) { _nullish($v) ? '' : $v };
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
_nullish($v) ? : 0 26 26
2197 44 ▶ if ($compare_type eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if ($compare_type eq "string") 10 34 44
2198 10 return $str->($av) cmp $str->($bv);
2199 }
2200 34 ▶ if ($compare_type eq 'auto') {
Branch: 1 branch
BranchTrueFalseTotal
if ($compare_type eq "auto") 9 25 34
2201 9 ▶ if (!_undef_p($av) && !_undef_p($bv) && looks_like_number($av // '') && looks_like_number($bv // '')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not _undef_p($av) || _undef_p($bv) and &looks_like_number(scalar($av // "")) and &looks_like_number(scalar($bv // ""))) 6 3 9
Condition53%7/13
not _undef_p($av) || _undef_p($bv) and &looks_like_number(scalar($av // "")) and &looks_like_number(scalar($bv // ""))
!ll&&!rl&&r
306
not _undef_p($av) || _undef_p($bv) and &looks_like_number(scalar($av // ""))
!ll&&!rl&&r
036
_undef_p($av) || _undef_p($bv)
l!l&&r!l&&!r
009
$av // ""
l!l
90
$bv // ""
l!l
60
MC/DC25%1/4
not _undef_p($av) || _undef_p($bv) and &looks_like_number(scalar($av // "")) and &looks_like_number(scalar($bv // ""))
_undef_p($av) _undef_p($bv) &looks_like_number(scalar($av // "")) &looks_like_number(scalar($bv // ""))
MC/DC0%0/1
$av // ""
$av
MC/DC0%0/1
$bv // ""
$bv
Truth table40%2/5
not(A || B) and C and D
A= _undef_p($av)B= _undef_p($bv)C= &looks_like_number(scalar($av // ""))D= &looks_like_number(scalar($bv // ""))
ABCDresult
1XXX0
01XX0
000X0
00100
00111
Truth table50%1/2
A
A= $av
Aresult
11
00
Truth table50%1/2
A
A= $bv
Aresult
11
00
2202 6 ▶ return ($av // 0) <=> ($bv // 0);
Condition50%2/4
$av // 0
l!l
60
$bv // 0
l!l
60
MC/DC0%0/1
$av // 0
$av
MC/DC0%0/1
$bv // 0
$bv
Truth table50%1/2
A
A= $av
Aresult
11
00
Truth table50%1/2
A
A= $bv
Aresult
11
00
2203 }
2204 3 return $str->($av) cmp $str->($bv);
2205 }
2206 25 ▶ return 0 if _undef_p($av) || _undef_p($bv);
Branch: 1 branch
BranchTrueFalseTotal
if _undef_p($av) or _undef_p($bv) 0 25 25
Condition33%1/3
_undef_p($av) or _undef_p($bv)
l!l&&r!l&&!r
0025
MC/DC0%0/2
_undef_p($av) or _undef_p($bv)
_undef_p($av) _undef_p($bv)
Truth table33%1/3
A or B
A= _undef_p($av)B= _undef_p($bv)
ABresult
1X1
011
000
2207 25 ▶ return ($av // 0) <=> ($bv // 0); # numeric
Condition100%4/4
$av // 0
l!l
241
$bv // 0
l!l
241
MC/DC100%1/1
$av // 0
$av
MC/DC100%1/1
$bv // 0
$bv
Truth table100%2/2
A
A= $av
Aresult
11
00
Truth table100%2/2
A
A= $bv
Aresult
11
00
2208 }
2209  
2210 # Fold an array into a scalar via the arithmetic-fold catalogue
2211 # (#1448 Tier C). Mirrors Go's `bf_reduce` and JS `reduce(fn, init)` /
2212 # `reduceRight(fn, init)` for the shapes `(acc, x) => acc <op> x` /
2213 # `(acc, x) => acc <op> x.field`:
2214 #
2215 # bf->reduce($recv, {
2216 # op => '+' | '*',
2217 # key_kind => 'self' | 'field',
2218 # key => '<field>', # when key_kind eq 'field'
2219 # type => 'numeric' | 'string',
2220 # init => <seed>, # number, or string for concat
2221 # direction => 'left' | 'right', # 'right' = reduceRight (default 'left')
2222 # })
2223 #
2224 # Numeric folds accumulate with `+` / `*` (non-numeric keys coalesce to
2225 # 0); string folds concatenate via `bf->string` (undef → ''). The init
2226 # seeds the accumulator, so an empty array returns it unchanged — exactly
2227 # like JS. `direction => 'right'` folds right-to-left (reduceRight); only
2228 # observable for string concat, since numeric sum / product commute.
2229 # Float stringification can diverge from Go's for inexact binary
2230 # fractions (e.g. 0.1 + 0.2); integer sums — the common case — agree.
2231 0 ▶sub reduce ($self, $recv, $opts = {}) {
Subroutine reduce: not called CC=17 SCAR=57.2
Pod undocumented
2232 0 ▶ my $op = $opts->{op} // '+';
Condition0%0/2
$opts->{"op"} // "+"
l!l
00
MC/DC0%0/1
$opts->{"op"} // "+"
$opts->{"op"}
Truth table0%0/2
A
A= $opts->{"op"}
Aresult
11
00
2233 0 ▶ my $key_kind = $opts->{key_kind} // 'self';
Condition0%0/2
$opts->{"key_kind"} // "self"
l!l
00
MC/DC0%0/1
$opts->{"key_kind"} // "self"
$opts->{"key_kind"}
Truth table0%0/2
A
A= $opts->{"key_kind"}
Aresult
11
00
2234 0 ▶ my $key = $opts->{key} // '';
Condition0%0/2
$opts->{"key"} // ""
l!l
00
MC/DC0%0/1
$opts->{"key"} // ""
$opts->{"key"}
Truth table0%0/2
A
A= $opts->{"key"}
Aresult
11
00
2235 0 ▶ my $type = $opts->{type} // 'numeric';
Condition0%0/2
$opts->{"type"} // "numeric"
l!l
00
MC/DC0%0/1
$opts->{"type"} // "numeric"
$opts->{"type"}
Truth table0%0/2
A
A= $opts->{"type"}
Aresult
11
00
2236 0 ▶ my $direction = $opts->{direction} // 'left';
Condition0%0/2
$opts->{"direction"} // "left"
l!l
00
MC/DC0%0/1
$opts->{"direction"} // "left"
$opts->{"direction"}
Truth table0%0/2
A
A= $opts->{"direction"}
Aresult
11
00
2237  
2238 0 ▶ my @items = ref($recv) eq 'ARRAY' ? @$recv : ();
Branch: 1 branch
BranchTrueFalseTotal
ref $recv eq 'ARRAY' ? : 0 0 0
2239 # reduceRight folds right-to-left; reversing the snapshot keeps the
2240 # single forward loop below. Only observable for string concat —
2241 # numeric sum / product commute. Qualify as CORE::reverse — this
2242 # package defines `sub reverse` (the `.reverse()` helper), so a bare
2243 # `reverse` is ambiguous under `use warnings`.
2244 0 ▶ @items = CORE::reverse(@items) if $direction eq 'right';
Branch: 1 branch
BranchTrueFalseTotal
if $direction eq "right" 0 0 0
2245 0 ▶ my $project = sub ($item) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
2246 0 ▶ $key_kind eq 'field' && ref($item) eq 'HASH' ? $item->{$key} : $item;
Branch: 1 branch
BranchTrueFalseTotal
$key_kind eq 'field' && ref $item eq 'HASH' ? : 0 0 0
Condition0%0/3
$key_kind eq "field" and ref $item eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
$key_kind eq "field" and ref $item eq "HASH"
$key_kind eq "field" ref $item eq "HASH"
Truth table0%0/3
A and B
A= $key_kind eq "field"B= ref $item eq "HASH"
ABresult
0X0
100
111
2247 0 };
2248 # The catalogue folds read a nil (`null` / `undefined`) item as '' / 0
2249 # (`string` / the numeric guard below), as they always have.
2250  
2251 0 ▶ if ($type eq 'string') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "string") 0 0 0
2252 0 ▶ my $acc = $opts->{init} // '';
Condition0%0/2
$opts->{"init"} // ""
l!l
00
MC/DC0%0/1
$opts->{"init"} // ""
$opts->{"init"}
Truth table0%0/2
A
A= $opts->{"init"}
Aresult
11
00
2253 0 $acc .= $self->string($project->($_)) for @items;
2254 0 return $acc;
2255 }
2256  
2257 0 ▶ my $acc = $opts->{init} // 0;
Condition0%0/2
$opts->{"init"} // 0
l!l
00
MC/DC0%0/1
$opts->{"init"} // 0
$opts->{"init"}
Truth table0%0/2
A
A= $opts->{"init"}
Aresult
11
00
2258 0 for my $item (@items) {
2259 0 my $n = $project->($item);
2260 # Guard `defined` before `looks_like_number` so a missing field
2261 # (undef) folds as 0 without an "uninitialized value" warning
2262 # under `use warnings` — matching the `$av // ''` style `sort` uses.
2263 0 ▶ $n = 0 if _nullish($n) || !looks_like_number($n);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($n) or not &looks_like_number($n) 0 0 0
Condition0%0/3
_nullish($n) or not &looks_like_number($n)
l!l&&r!l&&!r
000
MC/DC0%0/2
_nullish($n) or not &looks_like_number($n)
_nullish($n) not &looks_like_number($n)
Truth table0%0/3
A or not(B)
A= _nullish($n)B= not &looks_like_number($n)
ABresult
1X1
011
000
2264 0 ▶ $op eq '*' ? ($acc *= $n) : ($acc += $n);
Branch: 1 branch
BranchTrueFalseTotal
$op eq '*' ? : 0 0 0
2265 }
2266 0 return $acc;
2267 }
2268  
2269 # ---------------------------------------------------------------------------
2270 # JSX intrinsic-element spread (#1407)
2271 # ---------------------------------------------------------------------------
2272 #
2273 # Mirrors the JS `spreadAttrs` runtime
2274 # (`packages/client/src/runtime/spread-attrs.ts`) and the Go adapter's
2275 # `bf.SpreadAttrs` so SSR output stays byte-equal across the three
2276 # adapters. Generated Mojo templates invoke this as
2277 # `<%== bf->spread_attrs($bag) %>`.
2278 #
2279 # Skip rules: nil/false values, event handlers (`on[A-Z]…` shape
2280 # matching JS `key[2] === key[2].toUpperCase()` — true for any
2281 # character whose uppercase is itself, including digits and
2282 # underscore), `children`. `ref` is intentionally NOT filtered,
2283 # matching the JS reference.
2284 #
2285 # Key remap: className → class, htmlFor → for; SVG camelCase
2286 # attrs preserved (case-sensitive XML spec); other camelCase keys
2287 # lowered to kebab-case with a leading `-` for an initial
2288 # uppercase letter (mirrors JS `key.replace(/([A-Z])/g, '-$1')`).
2289 #
2290 # `style` is routed through `_style_to_css` so object literals
2291 # serialise to a real CSS string instead of Perl's default
2292 # `HASH(0x...)` form.
2293 #
2294 # Output is deterministic: keys are sorted alphabetically before
2295 # emission, matching the Go adapter's `sort.Strings(keys)` policy
2296 # and Mojo::JSON's marshal order.
2297 #
2298 # The return value is a Mojo::ByteStream so the calling template's
2299 # `<%==` raw-emit skips re-escaping (the helper has already
2300 # HTML-escaped each value).
2301  
2302 17 my %SVG_CAMEL_CASE_ATTRS = map { $_ => 1 } qw(
2303 allowReorder attributeName attributeType autoReverse
2304 baseFrequency baseProfile calcMode clipPathUnits
2305 contentScriptType contentStyleType diffuseConstant edgeMode
2306 externalResourcesRequired filterRes filterUnits glyphRef
2307 gradientTransform gradientUnits kernelMatrix kernelUnitLength
2308 keyPoints keySplines keyTimes lengthAdjust limitingConeAngle
2309 markerHeight markerUnits markerWidth maskContentUnits
2310 maskUnits numOctaves pathLength patternContentUnits
2311 patternTransform patternUnits pointsAtX pointsAtY pointsAtZ
2312 preserveAlpha preserveAspectRatio primitiveUnits refX refY
2313 repeatCount repeatDur requiredExtensions requiredFeatures
2314 specularConstant specularExponent spreadMethod startOffset
2315 stdDeviation stitchTiles surfaceScale systemLanguage
2316 tableValues targetX targetY textLength viewBox viewTarget
2317 xChannelSelector yChannelSelector zoomAndPan
2318 );
2319  
2320 23 ▶sub _to_attr_name ($key) {
Subroutine _to_attr_name: called CC=4 SCAR=13.9
2321 23 ▶ return 'class' if $key eq 'className';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "className" 1 22 23
2322 22 ▶ return 'for' if $key eq 'htmlFor';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "htmlFor" 1 21 22
2323 21 ▶ return $key if $SVG_CAMEL_CASE_ATTRS{$key};
Branch: 1 branch
BranchTrueFalseTotal
if $SVG_CAMEL_CASE_ATTRS{$key} 2 19 21
2324 # camelCase → kebab-case, with a leading `-` for an initial
2325 # uppercase letter (JS-reference parity, even though that case
2326 # produces an HTML-invalid attribute name — same documented
2327 # behaviour as the Go adapter's `toAttrName`).
2328 19 my $out = $key;
2329 19 $out =~ s/([A-Z])/-\L$1/g;
2330 19 return $out;
2331 }
2332  
2333 12 ▶sub _form_escape ($s) {
Subroutine _form_escape: called CC=3 SCAR=11.2
2334 # application/x-www-form-urlencoded serialisation, matching the browser's
2335 # `URLSearchParams` (which the SSR query render must equal): keep ASCII
2336 # alphanumerics and `* - . _`; encode every other byte as `%XX` (UPPER hex);
2337 # space → `+`. Non-ASCII is encoded byte-wise over its UTF-8 bytes.
2338 12 ▶ my $bytes = defined $s ? "$s" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $s ? : 12 0 12
2339 12 ▶ utf8::encode($bytes) if utf8::is_utf8($bytes);
Branch: 1 branch
BranchTrueFalseTotal
if utf8::is_utf8($bytes) 0 12 12
2340 12 $bytes =~ s/([^A-Za-z0-9*\-._ ])/sprintf('%%%02X', ord($1))/ge;
2341 12 $bytes =~ tr/ /+/;
2342 12 return $bytes;
2343 }
2344  
2345 26 ▶sub _html_escape ($value) {
Subroutine _html_escape: called CC=2 SCAR=7.0
2346 # HTML attribute-value escape for SSR string emission. The
2347 # spread bag's values reach the browser as part of a generated
2348 # `key="..."` substring inside the rendered HTML, so the
2349 # escape set has to cover everything that could break either
2350 # the surrounding double-quoted attribute or the enclosing
2351 # tag: `&`, `<`, `>`, `"`, and `'`. Matches Go's
2352 # `template.HTMLEscapeString` semantics byte-for-byte (using
2353 # `&#34;` / `&#39;` for quotes rather than the named entities)
2354 # so the SSR output is identical across the Go and Mojo
2355 # adapters (#1407, #1413 review). The CSR-side
2356 # `applyRestAttrs` calls `el.setAttribute(name, String(value))`
2357 # — which does its own DOM-level escaping in the browser —
2358 # so JS doesn't need an explicit escape pass; Perl/Go emit a
2359 # string, so we do.
2360 26 ▶ my $s = defined $value ? "$value" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $value ? : 26 0 26
2361 26 $s =~ s/&/&amp;/g;
2362 26 $s =~ s/</&lt;/g;
2363 26 $s =~ s/>/&gt;/g;
2364 26 $s =~ s/"/&#34;/g;
2365 26 $s =~ s/'/&#39;/g;
2366 26 return $s;
2367 }
2368  
2369 2 ▶sub _style_to_css ($value) {
Subroutine _style_to_css: called CC=7 SCAR=19.9
2370 2 ▶ return undef if _nullish($value);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($value) 0 2 2
2371 # Non-hashref values pass through stringified — matches the JS
2372 # `typeof value !== 'object'` branch in `styleToCss`.
2373 2 ▶ if (ref($value) ne 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value ne "HASH") 1 1 2
2374 1 my $s = "$value";
2375 1 ▶ return CORE::length $s ? $s : undef;
Branch: 1 branch
BranchTrueFalseTotal
CORE::length $s ? : 1 0 1
2376 }
2377 1 my @parts;
2378 1 for my $key (sort keys %$value) {
2379 2 my $v = $value->{$key};
2380 2 ▶ next if _nullish($v);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($v) 0 2 2
2381 2 my $prop = $key;
2382 2 $prop =~ s/([A-Z])/-\L$1/g;
2383 2 push @parts, "$prop:$v";
2384 }
2385 1 ▶ return @parts ? CORE::join(';', @parts) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@parts ? : 1 0 1
2386 }
2387  
2388  
2389 # Object-rest residual for a `.map()` destructure binding
2390 # (`{ id, ...rest } => …`, #2087 Phase B): returns a NEW hashref holding
2391 # every key of `$bag` except those named in `$keys` (an ARRAY ref of key
2392 # strings). This is plain JS destructure semantics (`const { id, ...rest }
2393 # = item`) — unlike `spread_attrs` below, there's no event-handler /
2394 # `children` filtering or key remapping here, because the residual is a
2395 # *value* the template may read fields off of (`$rest->{flag}`) or later
2396 # forward wholesale to `spread_attrs` (`{...rest}` on an element) — either
2397 # consumer applies its own rules downstream. A non-hashref `$bag` returns
2398 # an empty hashref rather than dying, so this stays safe as a `my` local
2399 # initializer even off unexpected/absent data (same defensive contract as
2400 # `spread_attrs`'s "no bag → nothing").
2401 # Structural scan for characters that could break a value out of a CSS
2402 # declaration -- ported byte-for-byte from Hono's own `hasUnsafeStyleValue`
2403 # (`hono/jsx/utils.ts`), the ORACLE this adapter's dynamic `style={{...}}`
2404 # values must match (#2261). NOT real CSSOM property validation. Every
2405 # character this scan tests is ASCII, so scanning by character (this file's
2406 # `use utf8` makes Perl string ops character-indexed) agrees with Hono's
2407 # UTF-16-code-unit scan for every input -- a non-ASCII codepoint can never
2408 # spuriously match one of these single-character comparisons.
2409 0 ▶sub _has_unsafe_style_value ($value) {
Subroutine _has_unsafe_style_value: not called CC=27 SCAR=66.3
2410 0 my $quote = '';
2411 0 my @block_stack;
2412 0 my $len = CORE::length $value;
2413 0 my $i = 0;
2414 0 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 0 0 0
2415 0 my $c = substr($value, $i, 1);
2416 0 ▶ if ($c eq '\\') {
Branch: 9 branches
BranchTrueFalseTotal
if ($c eq '\\') { } 0 0 0
elsif ($quote ne '') { } 0 0 0
elsif ($c eq '/' and $i + 1 < $len and substr($value, $i + 1, 1) eq '*') { } 0 0 0
elsif ($c eq '"' or $c eq q[']) { } 0 0 0
elsif ($c eq '(') { } 0 0 0
elsif ($c eq '[') { } 0 0 0
elsif ($c eq '{' or $c eq '}') { } 0 0 0
elsif ($c eq ')' or $c eq ']') { } 0 0 0
elsif ($c eq ';' and not @block_stack) { } 0 0 0
2417 0 ▶ return 1 if $i == $len - 1;
Branch: 1 branch
BranchTrueFalseTotal
if $i == $len - 1 0 0 0
2418 0 $i++;
2419 }
2420 elsif ($quote ne '') {
2421 0 ▶ return 1 if $c eq "\n" || $c eq "\f" || $c eq "\r";
Branch: 1 branch
BranchTrueFalseTotal
if $c eq "\n" or $c eq "\f" or $c eq "\r" 0 0 0
Condition0%0/6
$c eq "\n" or $c eq "\f" or $c eq "\r"
l!l&&r!l&&!r
000
$c eq "\n" or $c eq "\f"
l!l&&r!l&&!r
000
MC/DC0%0/3
$c eq "\n" or $c eq "\f" or $c eq "\r"
$c eq "\n" $c eq "\f" $c eq "\r"
Truth table0%0/4
A or B or C
A= $c eq "\n"B= $c eq "\f"C= $c eq "\r"
ABCresult
1XX1
01X1
0011
0000
2422 0 ▶ $quote = '' if $c eq $quote;
Branch: 1 branch
BranchTrueFalseTotal
if $c eq $quote 0 0 0
2423 }
2424 ▶ elsif ($c eq '/' && $i + 1 < $len && substr($value, $i + 1, 1) eq '*') {
Condition0%0/6
$c eq "/" and $i + 1 < $len and substr($value, $i + 1, 1) eq "*"
!ll&&!rl&&r
000
$c eq "/" and $i + 1 < $len
!ll&&!rl&&r
000
MC/DC0%0/3
$c eq "/" and $i + 1 < $len and substr($value, $i + 1, 1) eq "*"
$c eq "/" $i + 1 < $len substr($value, $i + 1, 1) eq "*"
Truth table0%0/4
A and B and C
A= $c eq "/"B= $i + 1 < $lenC= substr($value, $i + 1, 1) eq "*"
ABCresult
0XX0
10X0
1100
1111
2425 0 my $end = index($value, '*/', $i + 2);
2426 0 ▶ return 1 if $end < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 0 0 0
2427 0 $i = $end + 1;
2428 }
2429 ▶ elsif ($c eq '"' || $c eq "'") {
Condition0%0/3
$c eq "\"" or $c eq "'"
l!l&&r!l&&!r
000
MC/DC0%0/2
$c eq "\"" or $c eq "'"
$c eq "\"" $c eq "'"
Truth table0%0/3
A or B
A= $c eq "\""B= $c eq "'"
ABresult
1X1
011
000
2430 0 $quote = $c;
2431 }
2432 elsif ($c eq '(') {
2433 0 push @block_stack, ')';
2434 }
2435 elsif ($c eq '[') {
2436 0 push @block_stack, ']';
2437 }
2438 ▶ elsif ($c eq '{' || $c eq '}') {
Condition0%0/3
$c eq "{" or $c eq "}"
l!l&&r!l&&!r
000
MC/DC0%0/2
$c eq "{" or $c eq "}"
$c eq "{" $c eq "}"
Truth table0%0/3
A or B
A= $c eq "{"B= $c eq "}"
ABresult
1X1
011
000
2439 0 return 1;
2440 }
2441 ▶ elsif ($c eq ')' || $c eq ']') {
Condition0%0/3
$c eq ")" or $c eq "]"
l!l&&r!l&&!r
000
MC/DC0%0/2
$c eq ")" or $c eq "]"
$c eq ")" $c eq "]"
Truth table0%0/3
A or B
A= $c eq ")"B= $c eq "]"
ABresult
1X1
011
000
2442 0 ▶ return 1 if !@block_stack || $block_stack[-1] ne $c;
Branch: 1 branch
BranchTrueFalseTotal
if not @block_stack or $block_stack[-1] ne $c 0 0 0
Condition0%0/3
not @block_stack or $block_stack[-1] ne $c
l!l&&r!l&&!r
000
MC/DC0%0/2
not @block_stack or $block_stack[-1] ne $c
not @block_stack $block_stack[-1] ne $c
Truth table0%0/3
not(A) or B
A= not @block_stackB= $block_stack[-1] ne $c
ABresult
1X1
011
000
2443 0 pop @block_stack;
2444 }
2445 ▶ elsif ($c eq ';' && !@block_stack) {
Condition0%0/3
$c eq ";" and not @block_stack
!ll&&!rl&&r
000
MC/DC0%0/2
$c eq ";" and not @block_stack
$c eq ";" not @block_stack
Truth table0%0/3
A and not(B)
A= $c eq ";"B= not @block_stack
ABresult
0X0
100
111
2446 0 return 1;
2447 }
2448 0 $i++;
2449 }
2450 0 ▶ return ($quote ne '' || @block_stack) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$quote ne '' || @block_stack ? : 0 0 0
Condition0%0/3
$quote ne "" or @block_stack
l!l&&r!l&&!r
000
MC/DC0%0/2
$quote ne "" or @block_stack
$quote ne "" @block_stack
Truth table0%0/3
A or B
A= $quote ne ""B= @block_stack
ABresult
1X1
011
000
2451 }
2452  
2453 # Builds the CSS string for a `style={{...}}` JSX object-literal attribute
2454 # (#2261). `@pairs` alternates CSS key (always compile-time-known), then
2455 # value. A value that fails `_has_unsafe_style_value` (after JS-`String()`-
2456 # style stringification) is DROPPED -- the whole `key:value` pair is
2457 # omitted -- matching Hono's oracle exactly. The joined string is STILL
2458 # HTML-escaped (mirroring Hono's own `escapeToBuffer` call) since a
2459 # structurally "safe" value can still carry a literal `"`/`'`/`&`. Marked
2460 # raw so the calling template's raw-emit form doesn't re-escape it.
2461 0 ▶sub style_object ($self, @pairs) {
Subroutine style_object: not called CC=3 SCAR=24.8
Pod undocumented
2462 0 my @parts;
2463 0 ▶ for (my $i = 0; $i + 1 < @pairs; $i += 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i + 1 < @pairs) 0 0 0
2464 0 my $key = $self->string($pairs[$i]);
2465 0 my $value = $self->string($pairs[$i + 1]);
2466 0 ▶ next if _has_unsafe_style_value($value);
Branch: 1 branch
BranchTrueFalseTotal
if _has_unsafe_style_value($value) 0 0 0
2467 0 push @parts, _html_escape($key) . ":" . _html_escape($value);
2468 }
2469 0 return $self->backend->mark_raw(CORE::join(';', @parts));
2470 }
2471  
2472 8 ▶sub omit ($self, $bag, $keys) {
Subroutine omit: called CC=3 SCAR=11.0
Pod undocumented
2473 8 ▶ return {} unless defined $bag && ref($bag) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bag and ref $bag eq "HASH" 2 6 8
Condition100%3/3
defined $bag and ref $bag eq "HASH"
!ll&&!rl&&r
116
MC/DC100%2/2
defined $bag and ref $bag eq "HASH"
defined $bag ref $bag eq "HASH"
Truth table100%3/3
A and B
A= defined $bagB= ref $bag eq "HASH"
ABresult
0X0
100
111
2474 6 my %exclude = map { $_ => 1 } @$keys;
2475 6 return { map { $_ => $bag->{$_} } grep { !$exclude{$_} } keys %$bag };
2476 }
2477  
2478 25 ▶sub spread_attrs ($self, $bag) {
Subroutine spread_attrs: called CC=16 SCAR=27.8
Pod undocumented
2479 25 ▶ return '' unless defined $bag && ref($bag) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bag and ref $bag eq "HASH" 2 23 25
Condition100%3/3
defined $bag and ref $bag eq "HASH"
!ll&&!rl&&r
1123
MC/DC100%2/2
defined $bag and ref $bag eq "HASH"
defined $bag ref $bag eq "HASH"
Truth table100%3/3
A and B
A= defined $bagB= ref $bag eq "HASH"
ABresult
0X0
100
111
2480 23 my @parts;
2481 23 for my $key (sort keys %$bag) {
2482 # Event handlers: skip when key starts `on` and the third
2483 # character is its own uppercase form (uppercase letter,
2484 # digit, underscore, …). Mirrors the JS predicate.
2485 31 ▶ if (CORE::length($key) > 2 && substr($key, 0, 2) eq 'on') {
Branch: 1 branch
BranchTrueFalseTotal
if (CORE::length $key > 2 and substr($key, 0, 2) eq "on") 4 27 31
Condition100%3/3
CORE::length $key > 2 and substr($key, 0, 2) eq "on"
!ll&&!rl&&r
11164
MC/DC100%2/2
CORE::length $key > 2 and substr($key, 0, 2) eq "on"
CORE::length $key > 2 substr($key, 0, 2) eq "on"
Truth table100%3/3
A and B
A= CORE::length $key > 2B= substr($key, 0, 2) eq "on"
ABresult
0X0
100
111
2486 4 my $c = substr($key, 2, 1);
2487 4 ▶ next if CORE::uc($c) eq $c;
Branch: 1 branch
BranchTrueFalseTotal
if CORE::uc $c eq $c 3 1 4
2488 }
2489 28 ▶ next if $key eq 'children';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "children" 1 27 28
2490 27 my $val = $bag->{$key};
2491 # null / undefined → drop.
2492 27 ▶ next if _nullish($val);
Branch: 1 branch
BranchTrueFalseTotal
if _nullish($val) 1 26 27
2493 # Boolean values arrive as Mojo::JSON sentinel objects
2494 # (`Mojo::JSON::true` / `false`) — both from JSON-deserialised
2495 # props and from the test harness's `toPerlLiteral`
2496 # (which emits the sentinels rather than plain 0/1 to avoid
2497 # conflating booleans with numeric attribute values like
2498 # `tabindex="0"`). The contract is: callers MUST use the
2499 # sentinels for boolean values; plain Perl scalars 0/1
2500 # render as numeric attribute values, matching how JS
2501 # `spreadAttrs` treats a `0`/`1` JS number.
2502 26 ▶ if (ref($val) eq 'JSON::PP::Boolean' || ref($val) eq 'Mojo::JSON::_Bool') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq "JSON::PP::Boolean" or ref $val eq "Mojo::JSON::_Bool") 2 24 26
Condition66%2/3
ref $val eq "JSON::PP::Boolean" or ref $val eq "Mojo::JSON::_Bool"
l!l&&r!l&&!r
2024
MC/DC50%1/2
ref $val eq "JSON::PP::Boolean" or ref $val eq "Mojo::JSON::_Bool"
ref $val eq "JSON::PP::Boolean" ref $val eq "Mojo::JSON::_Bool"
Truth table66%2/3
A or B
A= ref $val eq "JSON::PP::Boolean"B= ref $val eq "Mojo::JSON::_Bool"
ABresult
1X1
011
000
2503 2 ▶ next unless $val;
Branch: 1 branch
BranchTrueFalseTotal
unless $val 1 1 2
2504 1 push @parts, _to_attr_name($key);
2505 1 next;
2506 }
2507 # `style` routes through `_style_to_css` so object literals
2508 # serialise to a real CSS string.
2509 24 ▶ if ($key eq 'style') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key eq "style") 2 22 24
2510 2 my $css = _style_to_css($val);
2511 2 ▶ next unless defined $css && CORE::length $css;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $css and CORE::length $css 0 2 2
Condition33%1/3
defined $css and CORE::length $css
!ll&&!rl&&r
002
MC/DC0%0/2
defined $css and CORE::length $css
defined $css CORE::length $css
Truth table33%1/3
A and B
A= defined $cssB= CORE::length $css
ABresult
0X0
100
111
2512 2 push @parts, qq{style="} . _html_escape($css) . qq{"};
2513 2 next;
2514 }
2515 22 my $name = _to_attr_name($key);
2516 22 push @parts, $name . qq{="} . _html_escape($val) . qq{"};
2517 }
2518 23 ▶ return '' unless @parts;
Branch: 1 branch
BranchTrueFalseTotal
unless @parts 1 22 23
2519 # Mark the result raw so the calling template's `<%==` raw-emit
2520 # doesn't re-escape the already-escaped values (the Mojo backend
2521 # returns a Mojo::ByteStream).
2522 22 return $self->backend->mark_raw(CORE::join(' ', @parts));
2523 }
2524  
2525 # ---------------------------------------------------------------------------
2526 # BarefootJS::Date -- this runtime's native date/time type, holding a single
2527 # epoch-ms integer. Exists so a Perl host can hand `date()` (above) a real
2528 # typed value instead of always going through the ISO-8601 string half of
2529 # the helper's contract (mirrors the Go runtime's `time.Time` / the Ruby
2530 # runtime's `Time` as the "native" receiver shape in spec/template-helpers.md
2531 # "date"). Deliberately minimal: one field, one constructor -- this is a
2532 # value wrapper, not a full calendar API.
2533 # ---------------------------------------------------------------------------
2534 package BarefootJS::Date;
2535  
2536 # Must carry its own literal $VERSION. META's `provides` is built by
2537 # Module::Metadata (see Makefile.PL), which reads each package's own
2538 # $VERSION and reports undef for one that has none -- and since a dist
2539 # with `provides` makes PAUSE index from META instead of scanning the
2540 # .pm files, an undef here is what PAUSE compares against the previously
2541 # indexed version. That reads as a *decreasing* version number and the
2542 # package drops out of the index -- which is what happened to this one in
2543 # BarefootJS-0.30.0, freezing it at the 0.29.0 tarball. It has to be
2544 # a literal string: Module::Metadata evaluates the version line in a Safe
2545 # compartment where `$BarefootJS::VERSION` is not visible and collapses to
2546 # 0. scripts/sync-perl-versions.ts bumps every `our $VERSION` line in the
2547 # file, so this stays in lockstep with the package version above.
2548 17 our $VERSION = "0.41.4";
2549  
2550 0 ▶sub new {
Subroutine new: not called CC=1 SCAR=6.9
2551 0 my ($class, $epoch_ms) = @_;
2552 0 return bless { epoch_ms => $epoch_ms }, $class;
2553 }
2554  
2555 package BarefootJS;
2556  
2557 17 1;
2558 __END__
↑ Summary lib/BarefootJS/Evaluator.pm »